I want to create an array of 100 size, with unique random integers from 1 to 999999 in C

126 views Asked by At

I want to create an array of 100 size, which its elements are unique random integers from 1 to 999999. My code doesn't give any error message or the output that I want. What is wrong with this?

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

#define N 100 
#define EMPTY -1

int main() {
    srand(time(NULL));
    int list[999999], A[N], i;

    for (i = 0; i < N; i++)
        A[i] = EMPTY;

    for (i = 0; i < 999999; i++) {
        list[i] = i + 1;
    }
    for (i = 0; i < 999999; i++) {
        int j = rand() % 999999;
        int temp = list[i];
        list[i] = list[j];
        list[j] = temp;
    }
    for (i = 0; i < N; i++) {
        A[i] = list[i];
    }

    for (i = 0; i < N; i++) {
        printf("%i\n", A[i]);
    }
}
1

There are 1 answers

0
chqrlie On

The initial loop is useless, the method is very inefficient, but the output should meet the goal...

Yet there might be an issue with the list array: it is very large and defining it as a local variable with automatic storage cause a stack overflow, depending on your target system. Try defining is as:

static int list[999999];

Here is an alternative for N small compared to 1000000:

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

#define N 100 

int main() {
    int A[N], i, j;

    srand(time(NULL));
    for (i = 0; i < N;) {
        int n = 1 + rand() % 999999;
        for (j = 0; j < i; j++) {
            if (A[j] == n)
                break;
        }
        if (i == j)
            A[i++] = n;
    }
    for (i = 0; i < N; i++) {
        printf("%i\n", A[i]);
    }
    return 0;
}