Could you please check my code to count the number of live cells

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 2029 Views - Last Post: 14 September 2012 - 03:11 AM Rate Topic: -----

#16 Judison   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 32
  • Joined: 08-August 12

Re: Could you please check my code to count the number of live cells

Posted 14 September 2012 - 02:19 AM

View Postcfoley, on 12 September 2012 - 05:21 AM, said:

Sure, I had two options and it would have affected the way I coded the for loops. Here is the way I did it:

int rowEnd = rowStart + 3;
// further down...
for(int r = rowStart; r < rowEnd; r++) {


And here is another sensible option, the one I think you were getting at.

int rowEnd = rowStart + 2;
// further down...
for(int r = rowStart; r <= rowEnd; r++) {


The only change is from +3 to +2 and the < in the loop is now <=.

In the first example, the +3 looks a bit strange. +2 in the second example makes more intuitive sense. But in Java for loops, most of the conditions take the form of i < array.length, i < string.length(), i < collection.size(), etc. <= often looks like a mistake.

So, I had to make a choice. Maybe my code would have been more readable if I had done this:

final int squareSize = 3
int rowEndExclusive = rowStart + squareSize;
// further down...
for(int r = rowStart; r < rowEndExclusive; r++) {


An interesting article on the subject (which I use as a guide when I have design choices like these):
http://www.cs.utexas...8xx/EWD831.html


Thanks alot for that! Yeah I was abit confused about why +3 rather than +2 but it all makes sense now thanks, one last think, why count--? what is its purpose, is it because board[row][col] refers to the cell itself which is not to be tested?
Was This Post Helpful? 0
  • +
  • -

#17 cfoley   User is offline

  • Cabbage
  • member icon

Reputation: 2425
  • View blog
  • Posts: 5,068
  • Joined: 11-December 07

Re: Could you please check my code to count the number of live cells

Posted 14 September 2012 - 03:11 AM

Yes, that's correct. The nested for loops I wrote would count the cell at [row][col] as a "neighbour". This will make the count too high if its value was true so the part of the code you are referring to is to correct the count.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2