rules.c (2019B)
1 #include <stdlib.h> 2 #include <time.h> 3 4 /* Populate a 2D array with 0's and 1's in a pseudo-random fashion. 5 * The population will be ratio*100% consisting of 1's 6 */ 7 void random_population(int **cells, int nx, int ny, double ratio) 8 { 9 int i, j; 10 srand(time(NULL)); 11 12 for (i=0; i<nx; i++) { 13 for (j=0; j<ny; j++) { 14 if ((double)rand()/RAND_MAX < ratio) 15 cells[i][j] = 1; 16 else 17 cells[i][j] = 0; 18 } 19 } 20 } 21 22 int find_neighbor_count(int **cells, int **neighbors, int nx, int ny) 23 { 24 int world_is_dead = 0; 25 int i, j, x, y; 26 int nneighbors; 27 28 /*for (i=1; i<nx-1; i++) { 29 for (j=1; j<ny-1; j++) {*/ 30 for (i=0; i<nx; i++) { 31 for (j=0; j<ny; j++) { 32 nneighbors = 0; 33 34 for (x=-1; x<2; x++) { 35 for (y=-1; y<2; y++) { 36 if (x != 0 && y != 0 && 37 i+x > 0 && i+x < nx && 38 j+y > 0 && j+y < ny) { 39 nneighbors += cells[i+x][j+y]; 40 } 41 } 42 } 43 neighbors[i][j] = nneighbors; 44 if (nneighbors > 0) 45 world_is_dead = 0; 46 } 47 } 48 49 if (world_is_dead == 1) 50 return 1; 51 else 52 return 0; 53 } 54 55 void cell_transitions(int **cells, int **neighbors, int nx, int ny) 56 { 57 int i, j, nneighbors; 58 for (i=0; i<nx; i++) { 59 for (j=0; j<ny; j++) { 60 nneighbors = neighbors[i][j]; 61 62 if (cells[i][j] == 1) { /* alive */ 63 if (nneighbors < 2) /* under-population */ 64 cells[i][j] = 0; 65 else if (nneighbors > 3) /* over-population */ 66 cells[i][j] = 0; 67 else /* survive */ 68 cells[i][j] = 1; 69 } else { /* dead */ 70 if (nneighbors == 3) /* reproduction */ 71 cells[i][j] = 1; 72 } 73 } 74 } 75 }