What is the method to avoid duplicate random numbers in the C language?
To generate unique random numbers in C language, you can use an array to store the generated numbers. Each time a new random number is generated, check if it already exists in the array. If it does, generate a new number until a unique one is produced. The specific steps are as follows:
- Create an array to store the randomly generated numbers, with the array size equal to the total number of unique random numbers needed.
- Generate a random number using the rand() function and compare it with elements in the array. If it already exists, generate a new one until a unique random number is generated.
- Store the generated unique random numbers in an array.
- Repeat the above steps until all unique random numbers are generated.
Here is a simple example code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_RANDOM 10
int main() {
int randomArray[NUM_RANDOM];
int i, j, r;
srand(time(NULL));
for (i = 0; i < NUM_RANDOM; i++) {
do {
r = rand() % 100; // 生成0-99之间的随机数
for (j = 0; j < i; j++) {
if (r == randomArray[j]) {
break;
}
}
} while (j < i); // 如果重复则重新生成
randomArray[i] = r;
printf("%d ", r);
}
return 0;
}
In this example, we generated 10 unique random numbers and displayed them on the screen. Keep in mind that in actual applications, the range and quantity of random numbers can be modified as needed.