How to generate N unique random numbers between min and max in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 8

int getRandom(const int min, const int max) {
    return (rand() % (max - min + 1)) + min; 
}

void generateUniqueRandomNumbers(int arr[], const int N, const int min, const int max) {
    int count = 0;
    while (count < N) {
        int num = getRandom(min, max); // Generate a random number within the specified range
        int isUnique = 1;
        for (int i = 0; i < count; i++) {
            if (arr[i] == num) {
                isUnique = 0;
                break;
            }
        }
        if (isUnique) {
            arr[count] = num;
            count++;
        }
    }
}

int main(void) {
    srand(time(NULL));
    const int N = SIZE; // Number of unique random numbers
    int arr[SIZE] = {0};

    generateUniqueRandomNumbers(arr, N, 1, 20);

    for (int i = 0; i < N; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}
 
   
/*
run:
   
20 13 4 17 1 7 16 14 
  
*/

 



answered Sep 24, 2024 by avibootz

Related questions

...