title: John Conway's Game of Life - Basic implementation in C
body: <blockquote>
    <p>John Conway's Game of Life - Set of Rules</p>
    
    <ol>
    <li>Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.</li>
    <li>Any live cell with more than three live neighbours dies, as if by overcrowding.</li>
    <li>Any live cell with two or three live neighbours lives on to the next generation.</li>
    <li>Any dead cell with exactly three live neighbours becomes a live cell.</li>
    </ol>
  </blockquote>
  
  <p>I've been working on implementing John Conway's Game of Life in C for the past few hours . What I'm trying to do is display the status of a board after K successive iterations . As input, I use the number of lines (int n ) and columns (int m) for a two-dimensional array, the components of the array (1 for live, 0 for dead)  and the number of generations (K) .</p>
  
  <p>I've managed to successfully implement the game using a plane approach.</p>
  
  <p><img src="https://i.stack.imgur.com/YwQMi.png" alt="enter image description here"></p>
  
  <p>What is meant by plane approach you can see in the left grid, where we check the neighbours of the black boxes to the N,NW,S,SW and so on . My algorithm works just fine for this, the 'life' function looks like this . For this to work, I've surrounded both marginal lines/columns with zeros.</p>
  
  <pre><code>void life(int a[100][100],int n,int m) {
    //Copies the main array to a temp array so changes can be entered into a grid
    //without effecting the other cells and the calculations being performed on them.
    int count;
    copy(a, temp, n ,m);
    for(int i = 1 ; i &lt;=n ; i++) {
      for(int j = 1; j &lt;= m; j++) {
        count = 0;
        count = a[i-1][j] + a[i][j-1] + a[i+1][j] + a[i][j+1] + a[i-1][j+1]
          + a[i+1][j-1] + a[i-1][j-1] + a[i+1][j+1];
        //The cell dies.
        if(count &lt; 2 || count &gt; 3)
          temp[i][j] = 0;
        //The cell stays the same.
        if(count == 2)
          temp[i][j] = a[i][j];
        //The cell either stays alive, or is "born".
        if(count == 3)
          temp[i][j] = 1;
      }
    }
    //Copies the completed temp array back to the main array.
    copy(temp, a, n ,m);
  }
  </code></pre>
  
  <p>But on the second grid we notice that each box has exactly eight neighbours, regardless of its position on the map. To check all the neighbours in this way, I'm supposed to use a toroidal approach.</p>
  
  <p>But I can't really grasp the concept, I mean I understand what a torrus is, but I just can't find a way to implement and write in code a checking function for this...</p>
  
  <p>These being said, can someone please explain how to think and maybe write such an approach ?</p>