I'm trying to build a memory game and I want to ask how I can generate a randomic number with just one repetition. Like 1-1, 2-2, 3-3. I will paste here my function that I created and tell me if I have to create another function just to create a condition to create just a pair from numbers.
// function to fulfill the table
void preencher_mesa(int matriz[4][4], int dificuldade)
{
int i, j;
int lim_col, lim_linha; // limits of the matriz
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) // difficulty == 1
{
matriz[i][j] = (rand()%3)+1;
}
else if(dificuldade == 2) // difficulty == 2
{
matriz[i][j] = (rand()%6)+1;
}
else if (dificuldade == 3) // difficulty == 3
{
matriz[i][j] = (rand()%8)+1;
}
}
}
mostrar_mesa(matriz); //showtable
}
If you have a 3x2 matrix that should be filled with the digits/numbers 1, 1, 2, 2, 3, 3 in some random permutation, then you could do something like:
You can use the Fisher-Yates shuffling algorithm. You might check in your copy of Knuth The Art of Computer Programming, Volume 2: Seminumerical Algorithms. Or you can look for expositions on Stack Overflow (such as Algorithm to select a single random combination of values, chosen because one of my Google searches also came across it).
Judging from the comments, you want duplicates from your
rand()surrogate, so this should work:Or, more succinctly:
Simply call
duprand()each time you want a random number. You will get the same value twice in a row. This code doesn't provide a resynchronization method; if you want one, you can write one easily enough:Sample output:
Note that because there's no call to
srand(), the permutation is fixed. (You might get a different result from what I show, but running this test multiple times will produce the same result each time on your machine.) Add a call tosrand()with an appropriate initialization, and you get different sequences. Hack and chop to suit your requirements for smaller matrices.