问题描述
我需要在 C++ 中创建算法实现以生成随机数到 f.e 表中,而无需重复和列表.
I need to create algorithm implementation in C++ to generate random numbers to f.e table without repeat and list.
我创建了类似的代码,但是当我将 n=32769 放入控制台程序停止工作时它停止工作.当我将数字放在 0-32768 范围内时,它就起作用了.知道这段代码有什么问题吗?编译时我没有错误/警告.
I created something code like that but it's stop working when I put n=32769 in console program stop working. When i put number in range 0-32768 it's works. Any idea what is wrong in this code?While compilation i had no errors/warnings.
#include <stdio.h>
#include <iostream>
#include <ctime>
int main()
{
clock_t start = clock();
int n;
std::cout << "n:";
std::cin >> n;
bool *used_numbers = new bool[n];
memset(used_numbers, false, sizeof(used_numbers[0]) * n);
int *permutation = new int[n];
srand(unsigned(std::time(NULL)));
int rnd_number;
for (int i = 0; i < n; i++)
{
rnd_number = rand() % n;
if (!used_numbers[rnd_number])
{
permutation[i] = rnd_number;
used_numbers[rnd_number] = true;
}
else
i--;
}
std::cout << "Permutation: \n ";
for (int k = 0; k < n; k++)
{
std::cout << permutation[k] << " ";
}
std::cout << std::endl;
printf("[Debug]: %lu ms\n", clock() - start);
getchar();
system("pause");
return 0;
}
推荐答案
rand() % n
永远不会给你一个大于 RAND_MAX 的数字.RAND_MAX 是 rand() 生成的数字的范围.
will never give you a number larger than RAND_MAX. RAND_MAX is the range of the numbers generated by rand().
如果使用大于 RAND_MAX 的 n 值,则在绘制第一个 RAND_MAX 数字后将永远循环.简而言之,没有数字可画了.
If you use a value of n larger than RAND_MAX, you will loop forever after you draw the first RAND_MAX numbers. Simply, there's no numbers left to draw.
您需要改进您的解决方案,以便能够生成更大的数字,或者使用更好的方法,例如改组更大的数字列表.
You need to improve your solution to be able to generate larger numbers, or use something better like shuffling a larger list of numbers.
你的算法有很多问题,但一个直接的简单解决方法是:
Your algorithm has many issues, but an immediate simple fix would be:
rnd_number = (rand() * (RAND_MAX + 1) + rand()) % n;
这篇关于C++ 无重复随机数生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!