在数组C++中生成唯一随机数
Generating Unique Random Numbers in Arrays C++
我已经编码了一个数组,里面有3个随机整数。但关键是我希望这3个随机数彼此不同(唯一的随机数)。我的问题是,即使这些数字是唯一的,我仍然会从中得到"糟糕"的读数。我用时间(NULL)为随机数播种,因此我在每个声明之间放置了一个Sleep(x)函数,以增加数字的多样性。下面的代码是main()函数中的所有代码。出于测试目的,我没有在代码中包含break语句,这样我就可以反复测试程序了。
srand((unsigned)time(NULL));
while(true)
{
//Generate 3 numbers
int a = rand() % 7 + 1;
Sleep(1000);
int b = rand() % 8 + 1;
Sleep(1000);
int c = rand() % 9 + 1;
int array[3] = { a , b , c };
//Check the numbers to make sure none of them equal each other
if( (array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]) )
{
//Print all numbers
for(int x = 0; x < 3; x++)
cout << array[x] << endl;
cout << "bad" << endl;
system("pause");
system("cls");
}
else
{
//Print all numbers
for(int x = 0; x < 3; x++)
cout << array[x] << endl;
cout << "good" << endl;
system("pause");
system("cls");
}
}
system("pause");
return 0;
当前检查的问题在于它检查由随机值表示的索引,而不是随机值本身,后者是前3个元素。
只需更换
if( (array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]) )
带有
if( (array[0] == array[1]) || (array[0] == array[2]) || (array[1] == array[2]) )
或者只是
if(a == b || a == c || b == c)
您似乎在使用Sleep
,这是一个与C库无关的Windows特定函数。CCD_ 2影响由CCD_ 3返回的序列,如果CCD_。
其次,您存储在a
、b
和c
中的随机数范围可能会导致以下行中的越界数组访问:
if( (array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]) )
array
只有3个元素,但a
、b
和c
中的值可能高于此。
既然您使用的是C++,请考虑利用C++标准库。
首先创建一个指定大小的矢量,并使用std::iota
将其填充为[0,10)范围内的值
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 0);
然后我们使用std::random_shuffle
对值进行重新排序。
std::random_shuffle (v.begin(), v.end());
并选择前三个值:
for (int i = 0; i < 3; ++i)
std::cout << v[i] << " ";
- 就像其他人说的,睡眠者什么都不做
- 洗牌的想法不太好。它比重新生成数字慢,直到你得到唯一的数字,而且它的扩展性也不太好。如果你想让你允许的数字范围很大,洗牌会变得昂贵得令人望而却步
我会这样做:
int a = rand() % 7 + 1;
int b = rand() % 8 + 1;
while( a == b )
b = rand() % 8 + 1;
int c = rand() % 9 + 1;
while(( a == c ) || ( b == c ))
c = rand() % 9 + 1;
int array[3] = { a , b , c };
您的"坏值"检查应该是:
如果((a==b)||(a==c)||(b==c))
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- 何时在引用或唯一指针上使用移动语义
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 计算排序向量的向量中唯一值的计数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 通过组合不同的类型来创建唯一的id
- if数组上的随机数
- 具有随机数的唯一向量
- 使用具有唯一随机数的结构数组创建多个对象
- 在C++中生成唯一的随机数
- 在向量中插入唯一的随机数
- 在多维数组中生成唯一的随机数C++
- 生成唯一的多个随机数
- 从一个特定的范围中生成一定数量的唯一随机数
- 在区间[0,n-1]中生成k个唯一随机数
- 输出 4 组 7 个升序有序和唯一随机数
- 在数组C++中生成唯一随机数
- 试图在每次迭代中产生一个唯一的随机数序列
- 使用线程生成唯一的随机数