3

Gday everybody,

I'm just trying to program the so called "life game". Forgot who invented it, but I find it pretty interesting. Please DO NOT post any links related to programming the game, as it would destroy my motivation ;)

The essential part of it is the playground. I need a two dimensional array, which is expandable in all directions.

E.g. I've got an array with 10*10 Fields in the beginning. I need to be able to add new fields in the direction of array[-1][-1] as well as in the direction of array[11][11] at the same time. I even need to be able to add a new item to field array[-1][10] or array[10][-10]. I need to be able to access the array into all possible 2D directions.

By the same time of writing this post, I just got an idea: What about having four arrays pointing towards all directions NORTH, EAST, SOUTH and WEST? Just having all arrays put next to each other, virtually pointing in the specified direction. Just like the example below. All Arrays put together form my playground. Would it be efficient, or are there simpler ways?

[][][] | [][][]
[][][] | [][][]
[][][] | [][][]
_______|_______
[][][] | [][][]
[][][] | [][][]
[][][] | [][][]

Thanks.

4

1 回答 1

2

Assuming you are using primitive arrays, expanding the matrix with a fixed number of cells could look like this:

boolean[][] gameBoard = new boolean[3][3];

public boolean[][] expandMatrixBy(boolean[][] matrix, int number) {
  int oldSize = matrix.length;
  int newSize = oldSize + 2 * number;
  boolean[][] result = new boolean[newSize][newSize];

  // Assume new cells should be dead, i.e. false..
  for (int row = number; row < oldSize + number; row++) {
    for (int col = number; col < oldSize + number; col++) {
      // ..copy only the existing cells into new locations.
      result[row][col] = matrix[row - number][col - number];
    }
  }
  return result;
}

// Calling this on a 3x3 matrix will produce 5x5 matrix, expanded by 1 on each side.
gameBoard = expandMatrixBy(gameBoard, 1);

And it's John Conway's Game of Life :-)

OPTION: This solution can be customized to enable expansion on selected sides with something like this:

enum Side { Left, Right, Top, Bottom };

public boolean[][] expandMatrixBy(boolean[][] matrix, int number, Set<Side> sides) {
  int oldSize = matrix.length;
  int newSize = oldSize + number * sides.size();
  boolean[][] result = new boolean[newSize][newSize];

  for (Side side : sides) {
    switch(side) {
      case Left:
        // Add number of columns on the left.

      case Right:
        // Add "number" of columns on the right.
    }
  }
  return result;
}

Set<Side> expandOnTheseSides = EnumSet.of(Side.Left, Side.Top);
gameBoard = expandMatrixBy(gameBoard, 1, expandOnTheseSides);

Good luck.

于 2013-04-14T09:41:27.150 回答