在数组C++中生成唯一随机数

Generating Unique Random Numbers in Arrays C++

本文关键字:唯一 随机数 数组 C++      更新时间:2023-10-16

我已经编码了一个数组,里面有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_。

其次,您存储在abc中的随机数范围可能会导致以下行中的越界数组访问:

if( (array[a] == array[b]) || (array[a] == array[c]) || (array[b] == array[c]) )

array只有3个元素,但abc中的值可能高于此。

既然您使用的是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] << " ";
  1. 就像其他人说的,睡眠者什么都不做
  2. 洗牌的想法不太好。它比重新生成数字慢,直到你得到唯一的数字,而且它的扩展性也不太好。如果你想让你允许的数字范围很大,洗牌会变得昂贵得令人望而却步

我会这样做:

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 };
  1. 您的"坏值"检查应该是:

    如果((a==b)||(a==c)||(b==c))