Advertisement
Guest User

conway

a guest
Oct 15th, 2017
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define WIDTH 30
  5. #define HEIGHT 20
  6.  
  7. int
  8. count_neighbour(int **grid, size_t h, size_t w)
  9. {
  10.         int c = 0;
  11.         int i, j;
  12.         for (i = -1; i < 2; i++) {
  13.                 for (j = -1; j < 2; j++) {
  14.                         if ((i == 0 && j == 0) || (h == 0 && i == -1)
  15.                             || (w == 0 && j == -1) || (h == HEIGHT-1 && i == 1)
  16.                             || (w == WIDTH-1 && j == 1))
  17.                                 continue;
  18.                         c += (grid[h+i][w+j] == 1 || grid[h+i][w+j] == 2);
  19.                 }
  20.         }
  21.         return c;
  22. }
  23.  
  24. void
  25. progress(int **grid)
  26. {
  27.         size_t h, w;
  28.         int c;
  29.  
  30.         for (h = 0; h < HEIGHT; h++) {
  31.                 for (w = 0; w < WIDTH; w++) {
  32.                         c = count_neighbour(grid, h, w);
  33.                         if (grid[h][w] == 0 && c == 3)
  34.                                 grid[h][w] = 3;
  35.                         else if (grid[h][w] == 1 && !(c == 2 || c == 3))
  36.                                 grid[h][w] = 2;
  37.                 }
  38.         }
  39.  
  40.         for (h = 0; h < HEIGHT; h++)
  41.                 for (w = 0; w < WIDTH; w++)
  42.                         grid[h][w] &= 1;
  43. }
  44.  
  45. void
  46. print_grid(int **grid)
  47. {
  48.         size_t h, w;
  49.         for (h = 0; h < HEIGHT; h++) {
  50.                 for (w = 0; w < WIDTH; w++)
  51.                         printf("%c", (grid[h][w] ? 'o' : ' '));
  52.                 printf("\n");
  53.         }
  54.         printf("------------------------------\n");
  55. }
  56.  
  57. int
  58. main(void)
  59. {
  60.         int **grid = malloc(sizeof(int) * HEIGHT);
  61.         for (int i = 0; i < HEIGHT; i++) {
  62.                 grid[i] = malloc(sizeof(int) * WIDTH);
  63.                 for (int j = 0; j < WIDTH; j++)
  64.                         grid[i][j] = arc4random_uniform(2);
  65.         }
  66.  
  67.         print_grid(grid);
  68.         for (;;) {
  69.                 getchar();
  70.                 progress(grid);
  71.                 print_grid(grid);
  72.         }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement