title: 2D Arrays - Error with counting neighbours algorithm (Conway's Game of Life)
body: <p>I am having problems with Conways Game of Life, specifically using a 2D integer array to count the number of true value "neighbours" from a 2D Boolean array (all arrays were scaled down to 10x10 for simplicity).</p>
  
  <p>I am using the following Algorithm for counting the number of neighboring cells within a 2D Boolean Array;</p>
  
  <pre><code>public static int neighbourCount(boolean[][] inputArray, int x, int y)
  {
      // X and Y co-ordinates for all spots around current point
      int[] xVals = {x - 1,   x - 1,  x - 1,  x,      x,      x + 1,  x + 1,  x + 1};
      int[] yVals = {y - 1,   y,      y + 1,  y - 1,  y + 1,  y - 1,  y,      y + 1};
  
      int nCount = 0;
  
      // Count neighbours algorithm
      for (int i = 0; i &lt; 8; i++)
      {
          if (xVals[i] &gt; 0 &amp;&amp; yVals[i] &gt; 0 &amp;&amp; xVals[i] &lt; 10 &amp;&amp; yVals[i] &lt; 10)
          {
              if (inputArray[(xVals[i])][(yVals[i])])
              {
                  nCount++;
              }
          }
      }
      return nCount;
  }
  </code></pre>
  
  <p>I used this algorithm specifically to prevent out of bounds exceptions.</p>
  
  <p>I used the following algorithm to print out the values;</p>
  
  <pre><code>    // Print countNeighbours Algorithm
      for (int i=0; i &lt; 10; i++)
      {
          for (int j=0; j &lt; 10; j++)
          {
              countNeighbours[i][j] = neighbourCount(gameBoard, i, j);
              System.out.print(" " + countNeighbours[i][j]);
          }
  
      System.out.println("");
      }
  </code></pre>
  
  <p>I tested the algorithm with the following initial values ( * = true Boolean values );</p>
  
  <pre><code>. . . . * . . . . .
  . . . * * * . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  </code></pre>
  
  <p>The expected results should have been;</p>
  
  <pre><code>. . 1 3 3 3 1 . . .
  . . 1 2 3 2 1 . . .
  . . 1 2 3 2 1 . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  </code></pre>
  
  <p>The results that were given were;</p>
  
  <pre><code>. . 1 2 3 2 1 . . .
  . . 1 1 2 1 1 . . .
  . . 1 2 3 2 1 . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  . . . . . . . . . .
  </code></pre>
  
  <p>I had considered using an alternative algorithm using a slightly bigger sized array to prevent the out of bounds exceptions, however it consisted of many if statements and looked very messy.</p>
  
  <p>Any helpful insight to this problem would be greatly appreciated and thanks in advance.</p>