Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1.     public static class GameOfLife {
  2.         private int currentGen = 0;
  3.         private int nextGen = 1;
  4.         private Cell headCell; // populated somehow
  5.  
  6.         public void tick() {
  7.             // visit entire graph
  8.             // we won't make assumptions about the number of neighbours and will handle backtracking by storing the current generation on the cell
  9.             tickCell(headCell);
  10.  
  11.             // now flip the generations
  12.             // we could use booleans but this allows us to potentially store more historical generations
  13.             int nextNextGen = currentGen;
  14.             currentGen = nextGen;
  15.             nextGen = nextNextGen;
  16.  
  17.         }
  18.  
  19.         private void tickCell(final Cell cell) {
  20.             if (cell.currentGen == nextGen) return; // already visited
  21.  
  22.             // Move this cell to the next generation
  23.             cell.currentGen = nextGen;
  24.  
  25.             // Visit all neighbours, counting live ones
  26.             int liveCount = 0;
  27.             for (var neighbour : cell.neighbours) {
  28.                 if (neighbour.genAlive[currentGen]) liveCount++;
  29.                 tickCell(neighbour);
  30.             }
  31.  
  32.             // Determine this cell's new generation state
  33.             // [deliberately verbose ifs for clarity]
  34.             if (cell.genAlive[currentGen]) {
  35.                 if (liveCount < 2) cell.genAlive[nextGen] = false; // you underpopulated bro
  36.                 else if (liveCount < 4) cell.genAlive[nextGen] = true; // you ok bro
  37.                 else cell.genAlive[nextGen] = false; // you sexed too much bro
  38.             } else {
  39.                 if (liveCount == 3) cell.genAlive[nextGen] = true; // you sexed back to life
  40.             }
  41.         }
  42.        
  43.         public static class Cell {
  44.             private int currentGen = 0;
  45.             private boolean[] genAlive; // populated somehow
  46.             private List<Cell> neighbours; // populated somehow
  47.         }
  48.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement