How to generate unique random numbers in C language?

In C language, the rand() function is used to generate random numbers. However, to generate non-repeating random numbers, the following method can be used:

  1. Use an array to store generated random numbers. Before generating a new random number each time, check if the number already exists in the array. If it does, generate a new random number until a unique one is obtained.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int nums[10]; // 存储生成的随机数
    int index = 0;

    srand((unsigned)time(NULL)); // 初始化随机数种子

    while (index < 10) {
        int new_num = rand() % 100; // 生成0~99的随机数

        // 检查数组中是否已经存在该随机数
        int i;
        int is_duplicate = 0;
        for (i = 0; i < index; i++) {
            if (nums[i] == new_num) {
                is_duplicate = 1;
                break;
            }
        }

        if (!is_duplicate) {
            nums[index] = new_num;
            index++;
        }
    }

    // 输出生成的不重复随机数
    for (int i = 0; i < 10; i++) {
        printf("%d ", nums[i]);
    }

    return 0;
}
  1. One option: You can generate a random permutation using the Fisher-Yates shuffle algorithm, then take the first n elements as non-repeating random numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void shuffleArray(int arr[], int n) {
    srand((unsigned)time(NULL));

    for (int i = n - 1; i > 0; i--) {
        int j = rand() % (i + 1);
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

int main() {
    int nums[10]; // 存储生成的随机数

    for (int i = 0; i < 10; i++) {
        nums[i] = i;
    }

    shuffleArray(nums, 10);

    // 输出生成的不重复随机数
    for (int i = 0; i < 10; i++) {
        printf("%d ", nums[i]);
    }

    return 0;
}

There are two methods provided above for generating unique random numbers, you can choose the appropriate method based on your specific needs.

bannerAds