Commit 80c44e7

mo khan <mo@mokhan.ca>
2014-10-28 01:22:06
generate a random world.
1 parent b98e022
Changed files (3)
src/gol.c
@@ -5,6 +5,8 @@
 #include <string.h>
 #include "gol.h"
 
+static const int NUMBER_OF_CELLS=9;
+
 int alive(char value) { return value == 'x' ? 1 : 0; };
 
 int west_of(int index) { return (index == 0 || index == 3 || index == 6) ?  index + 2 : index - 1; }
@@ -29,23 +31,21 @@ int living_neighbours_for(char* world, int index){
 }
 
 char* evolve(char* world) {
-  int number_of_cells = 9;
-  char* new_world = malloc(sizeof(char) * number_of_cells);
-  memset(new_world, 0, sizeof(char) * number_of_cells);
-  for (int i = 0; i < number_of_cells; i++) {
+  char* new_world = malloc(sizeof(char) * NUMBER_OF_CELLS);
+  memset(new_world, 0, sizeof(char) * NUMBER_OF_CELLS);
+  for (int i = 0; i < NUMBER_OF_CELLS; i++) {
     int neighbours = living_neighbours_for(world, i);
     if (alive(world[i])) {
-      new_world[i] = (neighbours >= 2 && neighbours <= 3) ? 'x' : ' ';
+      new_world[i] = (neighbours >= 2 && neighbours <= 3) ? ALIVE : DEAD;
     } else {
-      new_world[i] = neighbours == 3 ? 'x' : ' ';
+      new_world[i] = neighbours == 3 ? ALIVE : DEAD;
     }
   }
   return new_world;
 }
 
 void display(char* world) {
-  int number_of_cells = 9;
-  for (int i = 0; i < number_of_cells; i++) {
+  for (int i = 0; i < NUMBER_OF_CELLS; i++) {
     if (i % 3 == 0) { printf("\n"); }
     printf("%c", world[i]);
   }
src/gol.h
@@ -1,3 +1,6 @@
+static const char ALIVE='x';
+static const char DEAD=' ';
+
 int living_neighbours_for(char* world, int index);
 char* evolve(char* world);
 void display(char* world);
src/main.c
@@ -4,15 +4,25 @@
 #include <time.h>
 #include "gol.h"
 
+int random_life() {
+  return rand() % 2 == 0 ? ALIVE : DEAD;
+}
+
+char* random_world(){
+  char *world = malloc(sizeof(char) * 9);
+  for (int i = 0; i < 9; i++) {
+    world[i] = random_life();
+  }
+  return world;
+}
+
 int main(int argc, char **argv) {
-  char world[3][3] = {
-    { ' ', ' ', ' ' },
-    { 'x', 'x', 'x' },
-    { ' ', ' ', ' ' },
-  };
+  srand(time(NULL));
   system("clear");
-  char* new_world = *world;
+
+  char* new_world = random_world();
   int i = 0;
+
   while(1) {
     printf("GENERATION: %d\n", i);
     display(new_world);