Advertisement
Ioannis20x

Untitled

Dec 15th, 2022
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define DEAD 0
  5. #define ALIVE 1
  6.  
  7. #define ROWS 10
  8. #define COLS 10
  9.  
  10. int grid[ROWS][COLS];
  11.  
  12. /* Initializes the grid with a random pattern */
  13. void init_grid()
  14. {
  15. for (int i = 0; i < ROWS; i++)
  16. {
  17. for (int j = 0; j < COLS; j++)
  18. {
  19. grid[i][j] = rand() % 2;
  20. }
  21. }
  22. }
  23.  
  24. /* Returns the number of alive neighbors of the cell at (row, col) */
  25. int count_alive_neighbors(int row, int col)
  26. {
  27. int count = 0;
  28.  
  29. for (int i = row - 1; i <= row + 1; i++)
  30. {
  31. for (int j = col - 1; j <= col + 1; j++)
  32. {
  33. if (i == row && j == col)
  34. {
  35. continue;
  36. }
  37.  
  38. if (i >= 0 && i < ROWS && j >= 0 && j < COLS && grid[i][j] == ALIVE)
  39. {
  40. count++;
  41. }
  42. }
  43. }
  44.  
  45. return count;
  46. }
  47.  
  48. /* Updates the grid to the next generation according to the rules of the Game of Life */
  49. void update_grid()
  50. {
  51. int new_grid[ROWS][COLS];
  52.  
  53. for (int i = 0; i < ROWS; i++)
  54. {
  55. for (int j = 0; j < COLS; j++)
  56. {
  57. int alive_neighbors = count_alive_neighbors(i, j);
  58.  
  59. if (grid[i][j] == ALIVE)
  60. {
  61. /* Any live cell with two or three live neighbors survives */
  62. if (alive_neighbors == 2 || alive_neighbors == 3)
  63. {
  64. new_grid[i][j] = ALIVE;
  65. }
  66. else
  67. {
  68. new_grid[i][j] = DEAD;
  69. }
  70. }
  71. else
  72. {
  73. /* Any dead cell with three live neighbors becomes a live cell */
  74. if (alive_neighbors == 3)
  75. {
  76. new_grid[i][j] = ALIVE;
  77. }
  78. else
  79. {
  80. new_grid[i][j] = DEAD;
  81. }
  82. }
  83. }
  84. }
  85.  
  86. for (int i = 0; i < ROWS; i++)
  87. {
  88. for (int j = 0; j < COLS; j++)
  89. {
  90. grid[i][j] = new_grid[i][j];
  91. }
  92. }
  93. }
  94.  
  95. /* Prints the grid to the console */
  96. void print_grid()
  97. {
  98. for (int i= 0; i < ROWS; i++)
  99. {
  100. for (int j = 0; j < COLS; j++)
  101. {
  102. if (grid[i][j] == ALIVE)
  103. {
  104. printf("*");
  105. }
  106. else
  107. {
  108. printf(".");
  109. }
  110. }
  111.  
  112. printf("\n");
  113. }
  114.  
  115. printf("\n");
  116. }
  117.  
  118. int main()
  119. {
  120. init_grid();
  121.  
  122. for (int i = 0; i < 10; i++)
  123. {
  124. print_grid();
  125. update_grid();
  126. }
  127.  
  128. return 0;
  129. }
  130.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement