My thanks in advance to anyone who can fix my logic. I’m a beginner in every sense. I’ve read every post tagged w/”won.” I can’t get gdb to debug “won" and have manually mapped out i and j values (didn't want to struggle w/command line gdb).
Based upon check50’s results, the won function is broken. If I’ve got it wrong, please set me straight. When piping the 3x3 and 4x4 txt files, it gives an illegal move.
Here’s my logic:
Won requires iterating thru the array to verify values are in ascending order beginning with 1 and ending in (d * d) - 1.
Corner case is board[d – 1][d – 1] == 0, where board[d – 1][d – 1] < the preceding tile’s value.
My initial instinct wasn’t to create a counter variable, but I went with it because it was cleaner and I could learn a new approach. When employing a counter variable initialized to 1, the counter is 1 greater than the number of tiles.
Where d = 3, I’ve mapped out the values as below:
Whereas I easily grasped the concept of exceeding the array’s dimensions with “move,” when both i and j are < d, I don’t understand how I’m going off the board with "won" because I never see the values reach 3, but based off previous posts, it has to be the case and I can't code for the condition.
My first attempt was this expecting it to shut off the counter:
bool won(void)
{
int counter = 1;
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] == counter && counter < d * d - 1)
{
counter++;
}
else
{
return false;
}
}
}
return true;
}
I thought perhaps mixing values with the indices was the problem and adjusted the if statement to this:
if (board[i][j] == counter && board[i][j] < d * d)
{
counter++;
}
When that didn’t work, I thought I came up with a working albeit not very elegant solution with the if statement below:
if (board[i][j] == counter && board[i + 1][j] > board[i][j])
{
counter++;
}
Operating w/o gbd made me view the problem as where to get the loop to stop and j has to be < i which is < d, and board2 as [d – 1][d – 2]. I even tried embedding those parameters within the loop values, but the logic seemed flawed as j = 2 in the first 2 passes.
int counter = 1;
for (int i = 0; i < d - 1; i++)
{
for (int j = 0; j < d - 2; j++)
{
if (board[i][j] == counter)
{
counter++;
}
}
I am so sorry to be posting on an already-covered issue, but when I can’t get the code to work, I didn’t know what else to do. What confuses me most is no matter what change I make, piping the txt files and check50 return the same results, but I can’t discern what it’s telling me.