-1

In an 8-puzzle, when it finds the blank tile (which is represented by 0) in the board, it needs to get all neighboring boards that can be reached in one move.

As I have mapped a 2-dimensional board to a 1-dimensional array in my implementation, it does make sense to use index() in my code.

I can not figure out an elegant way to implement the neighbors() now so that it involved quite a bit of redundant code now.

public class Board {

private char[] tiles;
private int N;

private Board(char[] blocks) {
    N = (int) Math.sqrt(blocks.length);
    this.tiles = new char[blocks.length];
    System.arraycopy(blocks, 0, this.tiles, 0, N * N);
}

private void exch(int i, int j) {
    char swap = tiles[i];
    tiles[i] = tiles[j];
    tiles[j] = swap;
}

public Iterable<Board> neighbors()
{
    Stack<Board> neighbors = new Stack<>();
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (tiles[index(i, j)] == 0) {
                Board neighbor;
                if (i > 0) {
                    neighbor = new Board(tiles);
                    neighbor.exch(index(i, j), index(i - 1, j));
                    neighbors.push(neighbor);
                }

                if (j > 0) {
                    neighbor = new Board(tiles);
                    neighbor.exch(index(i, j), index(i, j - 1));
                    neighbors.push(neighbor);
                }

                if (i < N - 1) {
                    neighbor = new Board(tiles);
                    neighbor.exch(index(i, j), index(i + 1, j));
                    neighbors.push(neighbor);
                }

                if (j < N - 1) {
                    neighbor = new Board(tiles);
                    neighbor.exch(index(i, j), index(i, j + 1));
                    neighbors.push(neighbor);
                }
                break;
            }
        }
    }
    return neighbors;
}
}
pedim
  • 69
  • 2
  • 5

1 Answers1

0
public Stack<Board> update (int check, int checkB, int i, int, j, int index, int indexB, Stack<Board> neighbors, char[] tiles){
   if (check > checkB) {
   neighbor = new Board(tiles);
   neighbor.exch(index(i, j), index(i + index, j + indexB));
   neighbors.push(neighbor);
   }
   return neighbors;
}

Call it like this, 4 times for each condition :)

neighbor  = update (i, 0, i, j, -1, 0, neighbor, tiles )

would be equivalent to:

if (i > 0) {
    neighbor = new Board(tiles);
    neighbor.exch(index(i, j), index(i - 1, j));
    neighbors.push(neighbor);
}

If you want to cut down on variables in the function, you can also do it like:

public Stack<Board> update (boolean check, int i, int, j, int index, int indexB, Stack<Board> neighbor, char[] tiles){
   if (check) {

then just put the condition in the call

neighbor  = update ((i > 0), i, j, -1, 0, neighbor, tiles )
codeCompiler77
  • 508
  • 7
  • 22