0

0 down vote favorite

I am doing CS50 course now. I am trying to finish program fifteen. I have no idea what is wrong with won part of code.

I guess the problem is with that part of code:

    if (win[d-1][d-1] == d*d)
    {
        win[d-1][d-1] = 0;
        return true;
    }

I am trying to create a win matrix with proper configuration of numbers allowing to win the game and compare the win matrix with board matrix. If two arrays are the same, game is finished.

below I attach all code for won function:

/**
 * Returns true if game is won (i.e., board is in winning configuration), 
 * else false.
 */
bool won(void)

int win[DIM_MAX][DIM_MAX];

for (int i = 0; i < d; i++)
{
    for (int j = 0; j < d; j++)
    {

        if (win[d-1][d-1] == d*d)
        {
            win[d-1][d-1] = 0;
            return true;
        }

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

        win[i][j] = d*i + j + 1;
    }
}
return true;

I cannot figure out why function doesn't give value true for won function to quit the game.

Here is what console prints after using check50:

:( 3x3.txt wins the 3x3 board
   \ expected an exit code of 0, not a prompt for input
:( 4x4.txt wins the 4x4 board
   \ expected an exit code of 0, not a prompt for input
https://sandbox.cs50.net/checks/82c365cf5e614352a8a745b6f246aa93
1
  • How did you populate win matrix? And at what point do you do that? Also, instead of having a different win matrix for all values of d, wouldn't you rather have won() just go through your board checking to see if the numbers are in sequence? – ronga Oct 24 '16 at 1:21
1

It would be simpler to just compare against a simple int var and increment that var with each tile. However, your idea should still work.

Your code appears to populate the reference array as you loop through both arrays. Unfortunately, the code populates the reference array, win[][] after testing to see if the value in board[i][j] == win[i][j]. It will never pass. Along with that, it sets the last tile, at win[d-1][d-1] to 0 (correctly), but never checks the value at board[d-1][d-1].

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

1
  • ok, I moved win[i][j] = d*i + j + 1 on front of the loops as you said and it's working now. But as I understand my code correctly, condition board[d-1][d-1] == 0 is checked by if (board[i][j] != win[i][j]). another question is if instead of int win[DIM_MAX][DIM_MAX]; can I use int win[d-1][d-1] or just fill the matrix with zeros using int win[d-1][d-1] = {{0}}? – Daniel Oct 24 '16 at 10:11

You must log in to answer this question.

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