0

Trying my hands on fifteen and i am a beginner. My move function sucessfully can tell if the tiles are next to each other. and the swap part should work in theory ( i know i can code it much shorter) Can anyone see why my swapping goes haywire?

bool move(int tile)
{
    int swap=0;
    int tilerow;
    int tilecol;
    int zerocol;
    int zerorow;
     for(int i=0;i<d;i++)
        {
        for (int j=0;j<d;j++)
            {
            if (board[i][j]==tile)
                {
                tilerow=i;
                tilecol=j;
                }
            }
        }
     for(int i=0;i<d;i++)
        {
        for (int j=0;j<d;j++)
            {
            if (board[i][j]==0)
                {
                zerorow=i;
                zerocol=j;
                }
            }
        }
        if(tilerow-zerorow==1 && tilecol-zerocol==0)
            {
            swap=board[tilecol][tilerow];
            board[tilecol][tilerow]=board[zerocol][zerorow];
            board[zerocol][zerorow]=swap;

            return true;
            }
        else if(tilerow-zerorow==-1 && tilecol-zerocol==0)
            {
            swap=board[tilecol][tilerow];
            board[tilecol][tilerow]=board[zerocol][zerorow];
            board[zerocol][zerorow]=swap; 
            return true;
            }
        else if(tilerow-zerorow==0 && tilecol-zerocol==1)
            {
            swap=board[tilecol][tilerow];
            board[tilecol][tilerow]=board[zerocol][zerorow];
            board[zerocol][zerorow]=swap;
            return true;
            }
        else if(tilerow-zerorow==0 && tilecol-zerocol==-1)
            {
            swap=board[tilecol][tilerow];
            board[tilecol][tilerow]=board[zerocol][zerorow];
            board[zerocol][zerorow]=swap;
            return true;
            }
        else 

        return false;
return false;
}
1

You're detecting the row and column indices for the 0 tile and the target tile, but then reversing them, using row where you should have column and vice versa to do the swap.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • that must go down as a super dumb mistake. Thank you so much for spotting it
    – hmmmbob
    Jul 5 '16 at 15:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .