Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Life {
- int count(int[][] grid, int x, int y)
- {
- int size = grid.length;
- final int[][] xys = {
- {-1,-1}, {0,-1}, { 1,-1},
- {-1, 0}, { 1, 0},
- {-1, 1}, {0, 1}, { 1, 1}
- };
- int total=0;
- for(int[] xy : xys)
- {
- int nx=(x+xy[0]+size)%size, ny=(y+xy[1]+size)%size;
- total+=grid[ny][nx];
- }
- return total;
- }
- int[][] update(int[][] grid)
- {
- int size = grid.length;
- int[][] output = new int[size][size];
- for(int y=0;y<size;y++)
- {
- for(int x=0;x<size;x++)
- {
- int n = count(grid,x,y);
- int value = grid[y][x];
- output[y][x] = (n==3) ? 1 : (n==2) ? value : 0;
- }
- }
- return output;
- }
- void show(int[][] grid)
- {
- int size = grid.length;
- for(int[] xs : grid)
- {
- String line = "";
- for(int x : xs) line += x;
- System.out.println(line);
- }
- }
- public static void main(String[] args) {
- Life life = new Life();
- int[][] grid = {
- {1,0,0,0,1},
- {0,0,1,1,0},
- {0,1,0,1,0},
- {0,1,1,0,0},
- {1,0,0,0,1}
- };
- life.show(grid);
- for(int i=0;i<3;i++)
- {
- grid = life.update(grid);
- System.out.println();
- life.show(grid);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment