Random numbers in array

How would I make this not print out duplicates of the same number? Basically just print out 1-24 in a random order. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
void GenerateCards(int randomnums[]){
int randomvalues = 0;

srand((unsigned)time(NULL));
for(int i = 1; i <= 24; i++)
{
	randomvalues = rand() % 24 + 1;
	randomnums[i] = randomvalues;
}	

	return;
	
	
The easiest way is to fill the array with values 1-24 and then shuffle them at random.
Maybe something like this:
1
2
3
4
5
6
7
8
9
10
//this code belongs in the main function

//initialize array all zeroes
int randomnums[24]={0};
//fill with values 1-24
for (int i=0;i<24;i++)
randomnums[i]=i+1;
//shuffle positions at random
shuffle(randomnums);

But of course you need a shuffle function to make it work. Perhaps something like this?
1
2
3
4
5
6
7
8
9
10
void shuffle(int array[])
{
    for (int i=0;i<24;i++)
    {
      int temp=array[i];//use temp to hold i's value
      int temp2=rand()%24;//use temp2 to randomize where to swap with
      array[i]=array[temp2];//copy from randomized position to i's position
      array[temp2]=temp;//replace randomized position with temp's value
    }//repeat loop until all positions are shuffled
}

It's modified from an existing shuffle function I had on hand, and requires srand and the proper libraries, but it is likely you are already using them.

EDIT: Typo in the code needed correction. Outputting the array in order from this point should result in a random sequence, provided that the random number seed is properly set.
Last edited on
thank you
Topic archived. No new replies allowed.