class Life { public final static int ROWS = 3; public final static int COLS = ROWS; private final static double INITIAL_DENSITY = 0.3; private java.util.Random randy = new java.util.Random(); private boolean[][] board; /** constructor. * @param density The probabibility that any given location is * initially occupied (in [0,1]). */ public Life( double density ) { board = new boolean[ROWS][COLS]; // Initialize the entire board randomly: for (int r=0; r < ROWS; ++r) { this.initRowRandom(r, density); } } /** Constructor. * Uses a default initial density. * @see Life(double) */ public Life() { this(INITIAL_DENSITY); } /** Initialize one row of the board. * @param rowNum The row to initialize. * @param p the probability that any given cell will be filled. */ private void initRowRandom( int rowNum, double p ) { for (int c=0; c < COLS; ++c) { board[rowNum][c] = (this.randy.nextDouble() < p); } } /** * Return a string representing the board visually. */ public String toString() { String boardSoFar = ""; for (int r=0; r < ROWS; ++r) { boardSoFar += this.rowToString(r) + "\n"; } return boardSoFar; } /** UPdate the board to the next generation. */ void nextGen() { for (int r=0; r < ROWS; ++r) { this.nextGenRow(r); } } /** nextGenRow * set board[rowNum][...] for the next generation. */ void nextGenRow( int rowNum ) { for (int c=0; c < COLS; ++c) { //...update location board[rowNum][c] board[rowNum][c] = this.shouldBeAlive(rowNum,c); } } /** * Should a given board location be alive next generation? * @param r The row number to look at * @param c the col number to look at * @return whether a board[r][c] should be alive next generation? */ boolean shouldBeAlive( int r, int c ) { int numNeighbors = this.countNeighbors(r,c); if (this.board[r][c]) { // location is currently alive return ((numNeighbors == 2) || (numNeighbors==3)); } else { // location is currently dead return (numNeighbors==3); } } /** * Return the number of neighbors of a current board location. * @param r Which row of hte location. * @param c The location's column. * @return How many live neighbors board[r][c] has. */ int countNeighbors(int r, int c) { // Two problems with this: // (a) we can't add booleans; we want to convert f/t to 0/1 resp. // (b) we might index off the board! // Solution: make a method "countLocationIfValid(rowNum,colNum)", // and call that. return this.board[r-1][c-1] + this.board[r][c-1] + this.board[r+1][c-1] + this.board[r][c+1] + this.board[r-1][c] + this.baord[r+1][c]; } /** Return a string representing one row of the board. * @param rowNum which row to represent; must be in [0,ROWS). */ private String rowToString(int rowNum) { String rowSoFar = ""; for (int c=0; c < COLS; ++c) { if (board[rowNum][c]) { rowSoFar += "X"; } else { rowSoFar += "."; } // or, just: rowSoFar += (board[rowNum][c] ? "X" : "."); } return rowSoFar; } }