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

时间:2014-09-27 00:03:55

标签: c++ arrays random

我编写了一个内部有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 个答案:

答案 0 :(得分:5)

当前检查的问题是它检查由随机值表示的 indices ,而不是随机值本身,它们是前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)

答案 1 :(得分:0)

您似乎正在使用Sleep,这是一个与C库无关的特定于Windows的功能。 srand影响rand()返回的序列,如果srand()被赋予相同的种子,则该序列可重复。

其次,您在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] << " ";

答案 2 :(得分:0)

  1. 像其他人一样说,睡不做任何事。
  2. 洗牌的想法并不好。它比重新生成数字要慢,直到你获得独特的数字,并且它不能很好地扩展。如果您希望允许的数字范围很大,那么随机播放将变得非常昂贵。
  3. 我会做这样的事情:

    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. 检查&#34;错误值&#34;应该是:

      if((a == b)||(a == c)||(b == c))

相关问题