How to generate a random integer from a range [0, N] that is not in a unique integer list with C

1 Answer

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

int is_excluded(int num, const int *excluded, size_t excluded_size) {
    for (size_t i = 0; i < excluded_size; ++i) {
        if (excluded[i] == num) {
            return 1;
        }
    }
    
    return 0;
}

int random_excluding(int N, const int *excluded, size_t excluded_size) {
    if (excluded_size > (size_t)(N + 1)) {
        return -1;
    }

    srand((unsigned int)time(NULL));
    int num;
    do {
        num = rand() % (N + 1);
    } while (is_excluded(num, excluded, excluded_size));

    return num;
}

int main() {
    int excluded[] = {2, 5, 7};
    size_t excluded_size = sizeof(excluded) / sizeof(excluded[0]);
    int N = 14;

    int result = random_excluding(N, excluded, excluded_size);
    printf("%d\n", result);

    return 0;
}

 
 
/*
run:
   
6
   
*/

 



answered Nov 19, 2025 by avibootz

Related questions

...