Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class GameOfLife {
- private int currentGen = 0;
- private int nextGen = 1;
- private Cell headCell; // populated somehow
- public void tick() {
- // visit entire graph
- // we won't make assumptions about the number of neighbours and will handle backtracking by storing the current generation on the cell
- tickCell(headCell);
- // now flip the generations
- // we could use booleans but this allows us to potentially store more historical generations
- int nextNextGen = currentGen;
- currentGen = nextGen;
- nextGen = nextNextGen;
- }
- private void tickCell(final Cell cell) {
- if (cell.currentGen == nextGen) return; // already visited
- // Move this cell to the next generation
- cell.currentGen = nextGen;
- // Visit all neighbours, counting live ones
- int liveCount = 0;
- for (var neighbour : cell.neighbours) {
- if (neighbour.genAlive[currentGen]) liveCount++;
- tickCell(neighbour);
- }
- // Determine this cell's new generation state
- // [deliberately verbose ifs for clarity]
- if (cell.genAlive[currentGen]) {
- if (liveCount < 2) cell.genAlive[nextGen] = false; // you underpopulated bro
- else if (liveCount < 4) cell.genAlive[nextGen] = true; // you ok bro
- else cell.genAlive[nextGen] = false; // you sexed too much bro
- } else {
- if (liveCount == 3) cell.genAlive[nextGen] = true; // you sexed back to life
- }
- }
- public static class Cell {
- private int currentGen = 0;
- private boolean[] genAlive; // populated somehow
- private List<Cell> neighbours; // populated somehow
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement