Public feed
#894170
package gameoflife2;public class GameOfLife { /* * main() is the applications entry point. It'll configure a Colony instance, and run * stepColony() until there is no change or it has performed exactly 100 iterations. */ public static void main(String[] args) { for (String s: args) { System.out.println(s); } int width = args[0].length(); // Columns (Kolonner) int height = args.length; // Rows (Rader) // Find the width of the soon-to-be Colony instance. for (int i = 0; i < args.length; i++) { if (args[i].length() > width) { width = args[i].length(); } } // Create a new instance of Colony named "c". Colony c1 = new Colony(height, width); /* * Fill the new Colony c1, with values from String args[]. * * "*" = Live (true) * " " = Dead (false) * "." = Dead (false) */ int n = 0; for (int i = 0; i < c1.getHeight(); i++) { for (int j = 0 ; j < c1.getWidth(); j++) { if (args[i].charAt(0) == '*') { c1.setCell(i,j, true); } } // End for } // End for /* * Using stepColony() and nextColonyState() to update a new Colony either 100 * times and/or until the no cells are changed. */ Colony c2 = new Colony(height, width); int counter = 0; int changedCells; do { changedCells = stepColony(c1, c2); c1 = nextColonyState(c1); counter++; } while (counter <= 100 && changedCells > 0); } /* * willLive() returns the next state of a cell given the current state and * number of Live neighbours according to the rules of Game of Life. */ public static boolean willLive(boolean isLive, int liveNeighbours) { if(isLive && (liveNeighbours == 2 || liveNeighbours == 3)) return true; if(liveNeighbours == 3) return true; return false; } /* * stepColony() counts the number of cells which changed when given two Colony * instances, one being the current state and the other being the next state. */ public static int stepColony(Colony currentState, Colony nextState) { int changedCells = 0; for(int i = 0; i < currentState.getHeight(); i++) { for(int j = 0; j < currentState.getWidth(); j++) { boolean state = willLive(currentState.getCell(i, j), currentState.countNeighbours(i, j)); nextState.setCell(i, j, state); if(currentState.getCell(i, j) != nextState.getCell(i, j)) { changedCells += 1; } } } return changedCells; } /* * On our own initiative, we created a new method nextColonyState() which returns * a new Colony instance with the next state(s). */ private static Colony nextColonyState(Colony currentState) { Colony nextState = new Colony(currentState.getHeight(), currentState.getWidth()); for(int i = 0; i < currentState.getHeight(); i++) { for(int j = 0; j < currentState.getWidth(); j++) { boolean state = willLive(currentState.getCell(i, j), currentState.countNeighbours(i, j)); nextState.setCell(i, j, state); } } return nextState; } } // END CLASS GameOfLife