Question

Just thought I'd take a crack at Conway's Game of Life, but am seriously struggling...which is a surprise! Can someone maybe hint at algorithmic issues? Just a small nudge? This ain't homework.

#include <stdio.h>
#include <stdlib.h>

#define HEIGHT 10
#define WIDTH 10

int *gb[HEIGHT];
int *gb2[HEIGHT];

void copy() {
  int i, j;
  for (i = j = 0; i < HEIGHT; i++) {
    for (; j < WIDTH; j++) {
      gb2[i][j] = gb[i][j];
    }
  }
}

void init() {
  int i, j;
  for (i = 0; i < HEIGHT; i++) {
    gb [i] = malloc(sizeof(int)*WIDTH);
    gb2[i] = malloc(sizeof(int)*WIDTH);
  }
  for (i = j = 0; i < HEIGHT; i++) {
    for (; j < WIDTH; j++) {
      gb [i][j] = 0;
    }
  }
  gb[0][0] = 1;
  gb[0][1] = 1;
  gb[1][0] = 1;
  gb[1][1] = 1;
  copy();
}

void printg() {
  int i, j;
  printf("    ");
  for (i = 0; i < WIDTH; i++) {
    printf("%2d  ", i);
  }
  printf("\n\n");
  for (i = 0; i < HEIGHT; i++) {
    printf("%d   ", i);
    for (j = 0; j < WIDTH; j++) {
      printf(" %c  ", gb2[i][j]?'+':'-');
    }
    printf("\n");
  }
}

void ckill(int i, int j) {
  gb2[i][j] = 0;
}

void clive(int i, int j) {
  gb2[i][j] = 1;
}

void newgen() {
  int i, j = i = 1, n = 0;
  for (; i < HEIGHT-1; i++) {
    for (j = 0; j < WIDTH-1; j++) {
      if (gb[i][j+1]) n++;
      if (gb[i+1][j]) n++;
      if (gb[i+1][j+1]) n++;
      if (gb[i-1][j-1]) n++;
      if (gb[i][j-1]) n++;
      if (gb[i-1][j]) n++;
      if (gb[i+1][j-1]) n++;
      if (gb[i-1][j+1]) n++;

      if (n < 2) ckill(i, j);
      else if ((n == 2 || n == 3) && gb[i][j]) clive(i, j);
      else if (n > 3) ckill(i, j);
      else if (n == 3 && gb[i][j] == 0) clive(i, j);
    }
  }
}

int main() {
  int i;
  init();
  newgen();
  printg();
  for (i = 0; i < HEIGHT; i++) {
    free(gb[i]);
  }
}

This takes no input, but starts off with living cells at (0, 0), (0, 1), (1, 0), and (1, 1). After one generation, it should stay the same, but instead kills the cells so only (0, 0) and (1, 0) are alive.

Was it helpful?

Solution

In functions init and copy there's a double loop. Inner loop's counter j should be initialized in inner loop, not in outer.

In function newgen you're checking neighboring cells, all eight of them, even if cell is on the edge of the matrix. This results in accessing out of bound data, and undefined behavior.

A little note. Try to make good code, don't try to be smart. Initializing loop counter outside of loop is trying to be smart (but failing at it).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top