2

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);
}
George
  • 194
  • 2
  • 5
  • 13
  • You have the answer, you say not in any order ... it's just about reordering. – Iharob Al Asimi Nov 18 '15 at 23:30
  • 1
    If you don't want duplicates then you don't want a *random number*, you want a well defined *set* of numbers in *random order*. – J... Nov 18 '15 at 23:32
  • When I ran the program, I had the number 0844 two times. And I don't think it's only this number that appears twice. Let's say that I have produced numbers in this way: 0000, 0001, ..., 9999, not randomly. How can I reorder them in order to seem random? (question to your comment.) – George Nov 18 '15 at 23:32
  • @J... How is this possible? – George Nov 18 '15 at 23:34
  • @George See below ;) – J... Nov 18 '15 at 23:54

2 Answers2

6

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?

Community
  • 1
  • 1
Bug Hunter 219
  • 312
  • 1
  • 14
2

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;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97