2
Hello, I am making a memory game in c, and would like to know how to generate a random number without repetition. I will post what in the function so far. I will need to do another function only to check for repeated number?
void preencher_mesa(int matriz[4][4], int dificuldade)
{
int i,j;
int lim_col, lim_linha;
for(i=0; i<4; i++)
for(j=0;j<4;j++)
matriz[i][j] = 0;
if(dificuldade == 1)
{
lim_col = 3;
lim_linha = 2;
}
else if(dificuldade == 2)
{
lim_col = 4;
lim_linha = 2;
}
else if(dificuldade == 3)
{
lim_col = 4;
lim_linha = 4;
}
srand(time(NULL) );
for(i=0;i<lim_linha;i++)
{
for(j=0; j<lim_col;j++)
{
if(dificuldade == 1)
{
matriz[i][j] = (rand()%3)+1;
}
else if(dificuldade == 2)
{
matriz[i][j] = (rand()%6)+1;
}
else if (dificuldade == 3)
{
matriz[i][j] = (rand()%8)+1;
}
}
}
mostrar_mesa(matriz);
}
You can’t enter the values
1
,2
, and3
in an array of 6 positions without repeating! (difficulty == 1); You cannot enter values1
,2
,3
,4
,5
, and,6
in an array of 8 positions without repeating! (difficulty == 2); you cannot put 8 values in an array of 16 positions without repeating (3)– pmg
I really want them to repeat, but only once, because it’s a memory game
– Lucca Mello
Ok, the idea is the same as my answer. You fill the array with repeated values, shuffle the array, use the random values.
– pmg
I ended up creating this variable: int letters[16] = {1,1,2,2,3,3,4,5,5,6,6,7,7,8,8}; na main. But I wish that according to the level of difficulty there were only a couple of letters. Example => Difficulty 1 -> 3 pairs of cards then appear only (randomly) I don’t know, 1 and 1 , 4 and 4 , 7 and 7 @pmg
– Lucca Mello
The easiest way is to pick up 3 isolated numbers for the beginning of an array (
{1, 2, 3, 4, 5, 6, 7, 8}
==>{1, 4, 7}
); then extend this array principle ({1, 4, 7}
==>{1, 4, 7, 1, 4, 7}
); and finally shuffle the array. Note that the array can always be (or almost always) the same, only changes the initial number you consider. See the theme of my answer.– pmg