I always have the same randomized game of fifteen after randomizing it.
void init(void)
{
nombre = d*d-1;
for(int ligne = 0; ligne<d; ligne++){
for (int colonne= 0;colonne<d;colonne++){
board[ligne][colonne]=nombre;
nombre = nombre-1;
}
}
if(d%2==0){
printf("on a un nombre paire");
board[d-1][d-3]=1;
board[d-1][d-2]=2;
}
//i will always remain the same
int i = d * d - 1;
while (i > 0) {
int j = (rand() * i)%((d*d)-1);
int xi = i % d;
int yi = i / d;
int xj = j % d;
int yj = j / d;
if(xj<0){
printf("\nproblème, xj = %i\n",xj);
printf("i = %i\n",i);
break;
}
if(yj<0){
printf("\nproblème, yj = %i\n",yj);
printf("j = %i\n",j);
break;
}
swapTiles(xi, yi, xj, yj);
--i;
}
}
It always give:
0 7 6
5 4 2
3 1 8
swaptiles(i,j,k,l)
is the following
void swapTiles(i, j, k, l) {
printf("We entered swapTiles\n\n");
draw();
printf("\ntiles values:\n");
printf("xi: %i\n",i);
printf("yi: %i\n",j);
printf("xj: %i\n",k);
printf("yj: %i\n",l);
int temp = board[i][j];
printf("board[%i][%i] = %i\n",i,j,board[i][j]);
board[i][j] = board[k][l];
printf("board[%i][%i] = %i\n\n",k,l,board[k][l]);
board[k][l] = temp;
draw();
printf("\n\n");
}
I think the problem comes from rand()
. Would using generate
we used at the beginning of the program be better? Yet how to use it in a program and not in the command line?
Furthermore I had some difficulties when swapping. Indeed after randomizing given tile positions (xi,yi)
and (xj,yj)
I am able to get numbers that are below 0. That is why I used conditions and break
in my program. Yet, as far as I used ̀ rand()
and (d*d)-1
shouldn't I only have positive numbers?