So I need to write a program to generate 6 random numbers in a given range (1-90) without repetition. This is a classic question but all the answers that I found are based on discarding the numbers that you already generated until you get 6 of them and this is not a good way to do it in my opinion because you may change the distribution of the numbers. So this is what I tried to do:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SUP 90
#define N 6
#define SUP_N SUP-N
int main()
{
int array[SUP];
int i, k, a_size;
time_t t;
srand((unsigned)time(&t));
for(i = 0; i < SUP; i++)
{
array[i] = i + 1;
}
a_size = SUP;
for( i = 1; a_size > SUP_N; a_size--)
{
k = rand() % a_size;
printf("%2d\n", array[k]);
array[k] = array[a_size - 1];
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire