Reputation: 35
So I have an array board[][] whose values keep shuffling around. It is a square array with dimensions d*d. I want to check the array to see if all of its values are in ascending order.
for (int i = 0; i < d; i++)
{
for (int j = 0; i < d; i++)
{
if (board[i][j] == (d * i) + j + 1)
{
return true;
}
else
{
return false;
}
}
}
the problem is that as soon as the first element in the array board[0][0] = 1, it returns true, and ends my code. I don't know how to implement it so that it doesn't return true until all the elements in the array are in ascending order, from 1 to (d*d - 1).
Thank you!
Upvotes: 0
Views: 2957
Reputation: 15055
If I understood your question correctly I think you want to do this:
int Previous = board[0][0];
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] < Previous)
{
return false;
}
Previous = board[i][j];
}
}
return true; // Only at the end do we know that all elements are in ascending order
Problems with what you have are:
board
values against the indexes, not other board
valuesUpvotes: 3
Reputation: 979
This should work
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] != (d * i) + j + 1)
{
return false;
}
}
}
return true;
Upvotes: 2
Reputation: 23
1) First what you mean by ascending order (vertically, horizontally or in diagonal ?) 2) Replace your if statement if ((board[i][j] > board[i][j+1]) || (board[i][j] > board[i+1][j]))
Upvotes: 0
Reputation: 6936
Try replacing return true
with continue
:
for (int i = 0; i < d; i++)
{
for (int j = 0; i < d; i++)
{
if (board[i][j] == (d * i) + j + 1)
{
continue;
}
else
{
return false;
}
}
}
You can also remove the continue clause completely if you reverse the condition:
if (board[i][j] != (d * i) + j + 1)
{
return false;
}
Upvotes: 1