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

Generating Distinct Random Numbers in C++

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

对于编程作业的一部分,我需要生成多组 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 循环是否用于检查重复是否超出数组的边界?

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

您忘记将Duplicate重置回false。第一次设置为true时,它保持true,启用无限do...while循环。

从 1 到 50 的有序数组开始,然后通过 Fisher-Yates 洗牌进行洗牌。然后只取前 10 个数字。

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