|
| 1 | +public class Generation { |
| 2 | + |
| 3 | +private int[][] grid; |
| 4 | +private int rows; |
| 5 | +private int cols; |
| 6 | +private static char live = '@'; |
| 7 | +private static char dead = '*'; |
| 8 | + |
| 9 | + public Generation(int rows, int cols) { |
| 10 | + grid = new int[rows][cols]; |
| 11 | + for (int i = 0; i < rows; i++) { |
| 12 | + for (int j = 0; j < cols; j++) { |
| 13 | + grid[i][j] = (int)(Math.random() * 2); |
| 14 | + } |
| 15 | + } |
| 16 | + this.rows = rows; |
| 17 | + this.cols = cols; |
| 18 | + } |
| 19 | + |
| 20 | + public Generation(int[][] grid) { |
| 21 | + this.grid = grid; |
| 22 | + rows = grid.length; |
| 23 | + cols = grid[0].length; |
| 24 | + } |
| 25 | + |
| 26 | + public Generation next() {//generates the next generation |
| 27 | + int[][] next = new int[rows][cols]; |
| 28 | + for (int i = 0; i < rows; i++) { |
| 29 | + for (int j = 0; j < cols; j++) { |
| 30 | + next[i][j] = nextCell(i, j); |
| 31 | + } |
| 32 | + } |
| 33 | + return new Generation(next); |
| 34 | + } |
| 35 | + |
| 36 | + private int nextCell(int x, int y) {//given the coords of a cell, compute what it will become in the next generation |
| 37 | + int count = 0; |
| 38 | + for (int dX = -1; dX <= 1; dX++) {//dX and dY are offsets to check neighbors in a 3x3 area around a cell |
| 39 | + for (int dY = -1; dY <= 1; dY++) { |
| 40 | + count += (x+dX >= 0 && x+dX < rows && y+dY >= 0 && y+dY < cols) ? (grid[x+dX][y+dY]) : (0); |
| 41 | + } |
| 42 | + } |
| 43 | + count -= grid[x][y];//doesn't count itself |
| 44 | + |
| 45 | + int nextCell = grid[x][y];//the next cell starts out as being the current cell and only changes if the rules apply |
| 46 | + if (grid[x][y] == 0 && count == 3) { |
| 47 | + nextCell = 1; |
| 48 | + } else if (grid[x][y] == 1 && (count < 2 || count > 3)) { |
| 49 | + nextCell = 0; |
| 50 | + } |
| 51 | + |
| 52 | + return nextCell; |
| 53 | + } |
| 54 | + |
| 55 | + public static void setLive(char c) { |
| 56 | + live = c; |
| 57 | + } |
| 58 | + |
| 59 | + public static void setDead(char c) { |
| 60 | + dead = c; |
| 61 | + } |
| 62 | + |
| 63 | + public String toString() { |
| 64 | + String output = ""; |
| 65 | + for (int i = 0; i < rows; i++) { |
| 66 | + for (int j = 0; j < cols; j++) { |
| 67 | + output += (grid[i][j] == 1) ? live : dead; |
| 68 | + output += '\s'; |
| 69 | + } |
| 70 | + output += '\n'; |
| 71 | + } |
| 72 | + return output; |
| 73 | + } |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | +} |
0 commit comments