Reputation: 194
I have written a program that generates 4 random digits, that should appear on the screen like this: from 0000 to 9999 (not in ascending order necessarily, of course!).
The problem is that I have encountered numbers that are equal with each other. How can I fix it? I just want to produce 10.000 numbers, in the range 0000 to 9999, but not in any order: just "random".
Here is what I have written so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#define SIZE 10000
int main(){
srand(time(NULL));
int a[SIZE], b[SIZE], c[SIZE], d[SIZE], i;
FILE *fd = fopen("combinations_rand.txt", "w");
assert(fd);
for(i=0; i<SIZE; i++){
a[i] = rand()%10; //array of first digits
b[i] = rand()%10; //array of second digits, etc...
c[i] = rand()%10;
d[i] = rand()%10;
fprintf(fd, "%d%d%d%d\n", a[i], b[i], c[i], d[i]);
}
fclose(fd);
}
Upvotes: 2
Views: 349
Reputation: 344
Take an array of 10000 length and store the elements from 0 to 9999 in those. Then shuffle the array Shuffle array in C.
Then print the answer with leading zeros when needed Printing leading 0's in C?
Upvotes: 6
Reputation: 53016
What you should do is generate an array with the numbers from 0
to 9999
and then mix it up, like this
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define SIZE 10000
int main()
{
int numbers[SIZE];
srand(time(NULL));
/* Fill the array */
for (int i = 0 ; i < SIZE ; ++i)
numbers[i] = i;
/* Mix it */
for (int i = 0, j = rand() % SIZE ; i < SIZE ; ++i, j = rand() % SIZE)
{
int swap;
swap = numbers[i];
numbers[i] = numbers[j];
numbers[j] = swap;
}
/* Display it */
for (int i = 0 ; i < SIZE ; ++i)
fprintf(stdout, "%04d\n", numbers[i]);
return 0;
}
Upvotes: 2