views:

39

answers:

1

I have spent quite a while trying to write a program to implement Conway's game of life - [Link with more info.][1] . I am following some online guides and was given the majority of the functions. I wrote the "next" and "neighbours" methods shown below. Could anyone tell me if these are good implementations, and how they could be made better please ?

The point of the exercise was to not modify or change any of the other methods and just write the next method ! :)

--

+1  A: 

You don't need to copy the contents of cells to tempCells (the first nested loop in next). Instead, you can add one extra clause to the if-else in the next loop. Also, storing the result from neighbours may be a good idea for both speed and clarity.

for (int row = 0; row < cells.length ; row++)
    for (int col = 0 ; col < cells[row].length ; col++) {
       int n = neighbours(row,col);

       if (n > 3  ||  n < 2)
           tempCells[row][col] = false;
       else if (n == 3)
           tempCells[row][col] = true;
       else
           tempCells[row][col] = cells[row][col];
    }

(Apart from that, looks fine, but I haven't run and tested your code.)

larsmans
Thank you so much that makes it much better ! I was worried about the amount of for loops ! :) Wow ! I'm really impressed ! Thank you ! I dont really understand how adding this extra else clause works though, could you please explain it quickly ? It's copying into the array tempCells[row][col] the value that is in cells[row][col]....oooh I get it now ! Thank you ! :)