What I have to do is store a randomly selected pair of characters in a matrix and print it like this.
? # ¡ x
x ? # ¡
0 - + *
+ 0 - *
The problem is that I can't find a way to mark the characters that have come out twice, so as not to include them anymore.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char a[4][4];
char cartas[]={'#','%','@','0','*','!','<','x'};
int total=sizeof(cartas);
int main()
{
srand(time(0));
for (int i=0;i<4;i++)
{
for (int j=0;j<4;j++)
{
a[i][j]=cartas[rand()%total];
printf("\t%c",a[i][j]);
}
printf("\n\n");
}
}
Does anyone know of a way?
I would start by initializing the game array. It is not vital but it is important:
Then I would prepare the array to be able to easily iterate through it. The simplest is to linearize the array to work on one dimension. No problem because it
a[4][4]
reserves 16 consecutive memory locations:Now the array is filled. In order not to complicate things, we fill it in in order: first two copies of the first card, then two copies of the second...
Now the cards are shuffled. To do this, the array is iterated once and, for each position, another position is chosen at random with which to exchange its cards:
This sweep could be done two or more times.
And that's it, all cards shuffled, as you can check with a final loop: