Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Generate random numbers without repetition [duplicate]

Tags:

c

I want to generate random numbers between 1 and 13 without repetition I used this method, but it doesn't make sure there is no reputation.

for ( i = 0; i < 13; i++)
{
      array[i] = 1 + (rand() % 13);
}

Please help me. C language

like image 289
user3552818 Avatar asked Dec 11 '22 06:12

user3552818


1 Answers

As a comment said, Fill an array with numbers 1 through 13 then shuffle the array.

int array[13];

for (int i = 0; i < 13; i++) {     // fill array
    array[i] = i;
    printf("%d,", array[i]);
}
printf("\n done with population \n");
printf("here is the final array\n");

for (int i = 0; i < 13; i++) {    // shuffle array
    int temp = array[i];
    int randomIndex = rand() % 13;

    array[i]           = array[randomIndex];
    array[randomIndex] = temp;
}


for (int i = 0; i < 13; i++) {    // print array
    printf("%d,",array[i]);
}

Here is the sample output.

0,1,2,3,4,5,6,7,8,9,10,11,12,
 done with population 
here is the final array
11,4,5,6,10,8,7,1,0,9,2,12,3,

Note: I used the most basic sort I could. Use a better one if you want.

like image 156
Brian Tracy Avatar answered Jan 26 '23 00:01

Brian Tracy