class Life { public final static int ROWS = 5; public final static int COLS = ROWS; private final static double INITIAL_DENSITY = 0.3; private java.util.Random randy = new java.util.Random(); 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; } /** 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; } }