ptrelford

Conway's Game of Life

Apr 14th, 2012
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. class Life {
  2.  int count(int[][] grid, int x, int y)
  3.  {
  4.   int size = grid.length;
  5.   final int[][] xys = {
  6.    {-1,-1}, {0,-1}, { 1,-1},
  7.    {-1, 0},         { 1, 0},
  8.    {-1, 1}, {0, 1}, { 1, 1}
  9.   };
  10.   int total=0;
  11.   for(int[] xy : xys)
  12.   {
  13.    int nx=(x+xy[0]+size)%size, ny=(y+xy[1]+size)%size;
  14.    total+=grid[ny][nx];
  15.   }
  16.   return total;
  17.  }
  18.  int[][] update(int[][] grid)
  19.  {
  20.   int size = grid.length;
  21.   int[][] output = new int[size][size];
  22.   for(int y=0;y<size;y++)
  23.   {
  24.    for(int x=0;x<size;x++)
  25.    {
  26.     int n = count(grid,x,y);
  27.     int value = grid[y][x];
  28.     output[y][x] = (n==3) ? 1 : (n==2) ? value : 0;
  29.    }
  30.   }
  31.   return output;
  32.  }
  33.  void show(int[][] grid)
  34.  {
  35.   int size = grid.length;
  36.   for(int[] xs : grid)
  37.   {
  38.    String line = "";
  39.    for(int x : xs) line += x;
  40.    System.out.println(line);
  41.   }
  42.  }
  43.  public static void main(String[] args) {
  44.   Life life = new Life();
  45.   int[][] grid = {
  46.    {1,0,0,0,1},
  47.    {0,0,1,1,0},
  48.    {0,1,0,1,0},
  49.    {0,1,1,0,0},
  50.    {1,0,0,0,1}
  51.   };
  52.   life.show(grid);
  53.   for(int i=0;i<3;i++)
  54.   {
  55.     grid = life.update(grid);
  56.     System.out.println();
  57.     life.show(grid);
  58.   }
  59.  }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment