Rearranging and Checking Rows and Columns
The puzzle board
A sliding puzzle stores its numbered tiles in a 3-by-4 array. The player can slide a whole row or a whole column. The tile pushed off one end comes back at the other, so every slide is a rotation.
int[][] tiles = { {6, 1, 3, 4},
{5, 2, 7, 8},
{9, 10, 11, 12} };Rotating a row
Sliding row 0 to the left by one starts by saving the tile in column 0. Each later tile is copied one column to the left, and the saved tile goes at the end.
int first = tiles[0][0];
for (int col = 0; col < tiles[0].length - 1; col++)
{
tiles[0][col] = tiles[0][col + 1];
}
tiles[0][tiles[0].length - 1] = first;
Each assignment writes over a tile that's already safe, either saved in
first or copied one place left on the pass before. Row 0 becomes 1, 3, 4, and 6. A slide to the right runs from the other end. It saves the end tile, copies from the right, and puts the saved tile in column 0.Rotating a column
Sliding column 1 up by one is the left rotation turned on its side. The row index changes and the column index stays at 1.
int top = tiles[0][1];
for (int row = 1; row < tiles.length; row++)
{
tiles[row - 1][1] = tiles[row][1];
}
tiles[tiles.length - 1][1] = top;
Starting again from the original board, column 1 held 1, 2, and 10, and it now holds 2, 10, and 1. Each pass copies a tile into the row above it.
A shift is the same copying without the saved tile. The tile at the front end is lost. The far end keeps a second copy of its old tile unless a statement stores something else there, such as 0. A reverse of a row or column exchanges its two end elements and works inward, stopping at the middle.
Checking the board
The puzzle is solved when every tile holds its reading-order number, 1 through 12. That's an all-elements check over the whole array.
boolean solved = true;
for (int row = 0; row < tiles.length; row++)
{
for (int col = 0; col < tiles[row].length; col++)
{
if (tiles[row][col] != row * 4 + col + 1)
{
solved = false;
}
}
}
On the starting board, the 6 at row 0, column 0 should be a 1, so
solved becomes false and stays there.The same check can cover one designated column with a single loop. With the column index fixed at 3, each
tiles[row][3] must equal row * 4 + 4. Column 3 holds 4, 8, and 12, so that check stays true: the last column is already done.Two other checks follow patterns from earlier in the unit. Consecutive pairs in a row compare
tiles[row][col] with tiles[row][col + 1], so the column loop stops one column early. A duplicate within one row is found by comparing each of its elements with each element after it. The second index starts one past the first.