0

After two weeks struggle, I still can not come up with a solution to the won function. I divided the whole board into 3 areas: 1) rows except the last row (i.e. 0<=id+1 until (d-1)(d-2). Value at area 3 must value 0. If all of the three conditions are met, then the game must be won. but I do not know how to implement it.(because the first two conditions within the respective for loops, simply && cannot be used.) So, my logic is as follows: instead, if the first condition is not met, returning false, if the second condition is not met, again returning false, and if the third condition is not met, once again returning false; by so doing the remainder will mean all three conditions met and the game won (return true). But, the logic seems to have fraws. I am kind of give up and inclined to submit the fifteen uncompleted. My code is attached. Please give me any hints. Thank you in advance.

bool won(void)
{
    // check rows except the last one if each tile is in ascending order starting at 1
    int n = 1;
    int temp = (d-1)*d+1;
    for (int i = 0; i < d-1; i++) 
    {
        for (int j = 0; j < d; j++)
        {
            if(board[i][j] != n)
            {
                return false;
                n++;
            }
        }
    }
    //last row other than the last one must increment starting with (d-1)*d + 1
    for(int j = 0; j < d-1; j++)  
    {
        if(board[d-1][j] != temp)
        {
            return false;
            temp++;
        }
    }
    if( (board[d-1][d-1] != 0) //board[d-1][d-1] must be blanktile
    {
        return false;
    }

    return true;
}

1 Answer 1

1

There are more elegant implementations, but most notably:

        if(board[i][j] != n)
        {
            return false;
            n++;
        }

The n++ is never performed. You probably meant something like

        if(board[i][j] != n)
        {
            return false;
        }
        else
        {
            n++;
        }

Same for the second part (you could continue using n instead of temp)

You could even do everything in one loop (or nested loops), using && (who keeps you from using it?) for the last test case like

if (n != d*d && board[i][j] != n)

I'm not testing for 0 there, as if you implemented move right, if (d*d-1) tiles match, the (d*d)th has to be 0.

Or use

if (board[i][j] != n % (d*d))

with the modulo operator (division remainder), that one also tests for 0.

These are a lot easier than dividing the board into three areas.

1
  • Thank you very much for your inspiring advice.Due to some other work, I did not have time to visit this site and respond to you earlier. With your advice, I was able to "won" the game, and will be released from the Night mare of Fifteen any more. I really appreciate your advice. Nov 27, 2016 at 5:45

You must log in to answer this question.

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