The simplest and universally accepted solution is to use the algorithm Fisher-Yates which consists of storing all possible numbers, so you have control that they will not repeat themselves, and only then randomly shuffle these numbers, picking up the first numbers already properly shuffled.
Simple, complete solution without dependencies:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN 1
#define MAX 1000000
#define QTDE 10000 //precisa ser menor que MAX
void shuffle(int *array) {
for (int i = MAX - MIN - 1; i > 0; i--) {
int j = rand() % (i + 1);
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
int main(void) {
srand(time(NULL));
int * numeros = malloc((MAX - MIN) * sizeof(int));
if (!numeros) exit(EXIT_FAILURE);
for (int i = 0; i < MAX - MIN; i++) {
numeros[i] = i + MIN;
}
shuffle(numeros);
for (int i = 0; i < QTDE; i++) {
printf("%d\n", numeros[i]);
}
return 0;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I believe that this form is sufficient, to generate a sequence not biased would complicate a little more, in general the staff works this way in simple things. If you want to insist you could create a function to generate the random numbers, which would take a lot more time, something like that:
int rand_int(int n) {
int limit = RAND_MAX - RAND_MAX % n;
int rnd;
do {
rnd = rand();
} while (rnd >= limit);
return rnd % n;
}
But to tell you the truth I don’t know if for this volume of numbers that can be drawn and the disproportion that will be used, it pays to do this type of algorithm. Will depend on the need and availability of resources.
I believe that storing in file is not the problem, I did not put anything.
Did the answer solve your problem? Do you think you can accept it now? See [tour] to understand how it works. It would be helpful to indicate to everyone that the solution was useful and satisfactory for you. You can also vote on any question or answer you find useful on the entire site.
– Maniero