在C ++中生成不同的随机数

时间:2014-01-10 00:37:11

标签: c++

对于编程分配的一部分,我需要生成多组10个数字,范围为1到50,每个单独的集合中没有重复,所以我创建了以下代码:

int Numbers[10]; //array to store the random numbers in
bool Duplicate; //variable to check or number is already used

srand(time(NULL)); //seeding the random number generator

// do while loop used to allow user to generate multiple sets 
do {

     Duplicate = false; // set check to false

     //for loop to generate a complete set of 10 random numbers
     for (int I = 0; I < 10; I++)
     {

        // do while loop used to generate random numbers until a distinct random number is generated
         do
         {
         Numbers[I] = (rand()%50) + 1; // generates a random number 1 - 50 and stores it into Numbers[I]

         // for loop used to check the other numbers in set for any repeats
         for (int J = I - 1; J > -1; J--) // works backwards from the recently generated element to element 0
              if (Numbers[I] == Numbers[J]) //checks if number is already used
                   Duplicate = true; //sets Duplicate to true to indicate there is a repeat

         } while (Duplicate); //loops until a new, distinct number is generated
     }

//at this point in the program we should have an array Numbers[] with a set of 10 unique random numbers 1 - 50

     // loop to print numbers to the screen
     for (int I = 0; I < 10; I++)
          cout << Numbers[I] << " "; // printing the element to the screen

cout << endl;
cout << "Do you want to run the program again (Y/N): "; // Asks user if they want to create another set of 10 numbers
char Answer; // used to store users answer
cin >> Answer; // stores users answer

} while (Answer == 'Y' || Answer == 'y'); // loop program if the user wants to generate another set

但是,我似乎遇到了生成随机数的do while循环,直到生成一个新的不同数字。 经过一些测试和修补,我发现我在某种程度上创造了一个无限循环,无法弄清楚问题。

我认为可能导致问题的一些想法: - rand函数如何更改种子,是否更改种子以创建新的伪随机数? - 我的for循环检查重复超出数组范围的重复吗?

任何建议和提示都将不胜感激。

3 个答案:

答案 0 :(得分:2)

您忘记将Duplicate重置为false。首次将其设置为true,它仍为true,从而启用无限do...while循环。

答案 1 :(得分:1)

从1到50的有序数组开始,然后通过Fisher-Yates shuffle对其进行随机播放。然后只需要前10个数字。

答案 2 :(得分:1)

请注意,在do-while循环开始时不要将Duplicate重新初始化为false,这意味着在您有一个重复的随机数之后 - Duplicate设置为true并且永远保持为true - 您的do-while循环将运行永远。