Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Life
- {
- public static void main(string[] args)
- {
- int row = 6;
- int column = 8;
- int seed = 7;
- int generations = 6;
- boolean[][] matrix = createMatrix(row, column);
- for (int i = 0; i <= generations ; i++)
- {
- // if we're in our first generation, just create the matrix
- if (i == 0)
- {
- matrix = fillMatrix(matrix, seed);
- }
- // otherwise, get the next generation
- else
- {
- matrix = getNextGeneration(matrix);
- }
- printMatrix(matrix);
- }
- }
- public static boolean[][] createMatrix(int length, int width)
- {
- return new boolean[length][width]();
- }
- public static boolean[][] fillMatrix(boolean[][] matrix, int seed)
- {
- Random rnd = new Random(seed);
- // iterate through all rows except the first and last
- for (int i = 1 ; i <= matrix.length - 1; i++)
- {
- // iterate through all columns except the first and last
- for (int j = 1 ; j <= matrix[i].length - 1; j++)
- {
- matrix[i][j] = rnd.nextBoolean();
- }
- }
- return matrix;
- }
- public static boolean[][] getNextGeneration(boolean[][] currentGeneration)
- {
- int neighbors = 0;
- int length = currentGeneration.length;
- int width = currentGeneration[0].length;
- boolean[][] currentGeneration = new boolean[length][width]();
- for (int i = 1 ; i <= currentGeneration.length - 1; i++)
- {
- // iterate through all columns except the first and last
- for (int j = 1 ; j <= currentGeneration[i].length - 1; j++)
- {
- // check each of the cell's neighbors, and increment the neighbors variable above
- // change the number in this if statement to correspond to what the lab says makes a cell die
- if (neighbors > 3)
- {
- // cell dies
- currentGeneration[i][j] = false;
- }
- else
- {
- // cell stays alive
- currentGeneration[i][j] = true;
- }
- }
- neighbors = 0;
- }
- return currentGeneration;
- }
- public static void printMatrix(boolean[][] matrix)
- {
- for (int i = 0 ; i != matrix.length ; i++)
- {
- for (int j = 0 ; j != matrix[i].length ; j++)
- {
- String output = "- ";
- if (matrix[i][j])
- {
- output = "# ";
- }
- System.out.print(output);
- }
- // print this after each row so that it prints the next row on a new line
- System.out.println("");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement