1

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]);
    }
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
fatih
  • 47
  • 3
  • Why doesn't it? What's exactly wrong with it? – Arkadiusz Drabczyk Jan 01 '22 at 14:17
  • The initial loop is useless, the method is very inefficient, but the output should meet the goal... – chqrlie Jan 01 '22 at 14:24
  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Filburt Jan 01 '22 at 14:30
  • @Exampleperson: normally, Windows gives 1 MiB of stack space but Unix-like systems (Linux etc) give 8 MiB of stack space. On Windows, the code could crash for lack of space; on Unix, that's less likely to be the problem. – Jonathan Leffler Jan 01 '22 at 14:45
  • 1
    Look up the [Fisher-Yates Shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). See also [Unique non-repeating random numbers in O(1) time?](https://stackoverflow.com/q/196017/15168) – Jonathan Leffler Jan 01 '22 at 14:54

1 Answers1

0

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;
}
rici
  • 234,347
  • 28
  • 237
  • 341
chqrlie
  • 131,814
  • 10
  • 121
  • 189