-1

I have looked around for this question, there are some answers about the question, but none that i really understand/or is not suitable for me.

So my problem is to check for 8 neighbors in an 2d array containing chars, either * or O.

Code:

aliveCheck = isAlive(g,row,column-1);
if(aliveCheck){
    aliveCounter++;
}

aliveCheck = isAlive(g,row,column+1);
if(aliveCheck == 1){
    aliveCounter++;
}

aliveCheck = isAlive(g,row+1,column);
if(aliveCheck == 1){
    aliveCounter++;
}

Etc for all the 8 neighbours, this works, but I'm not happy with the solution.

isAlive() is a simple function to findout if a coordinate is * or O.

Anyone got a better solution to this problem or got any tips on how to improve it?

Thanks

uzr
  • 1,210
  • 1
  • 13
  • 26
  • 1
    In what way are you `unhappy` with the solution? – nhgrif Nov 04 '13 at 23:03
  • You could try looping with row and column offsets and writing one block of code that adds the offets and only changing the offsets each loop. – Avery Nov 04 '13 at 23:07
  • The code gets really long when there are 8 if statements after each other, and im interested in learning some new ways to aproach this problem @nhgrif – uzr Nov 04 '13 at 23:07
  • just put it in a function. To me, using the loop method described in the answers makes it more confusing of what you are trying to accomplish. – clcto Nov 04 '13 at 23:17
  • Out of curiosity, trying to solve Conway's game of life? – Alex Nov 04 '13 at 23:28
  • @RhinoFeeder Yes, you are correct. – uzr Nov 04 '13 at 23:53

1 Answers1

2
for(int i=-1, i<=1; ++i) {
    for(int j=-1; j<=1; ++j {
        if((i || j) && isAlive(g,row+i,column+j)) {
            aliveCounter++; } } }

This method assumes that i-1, i+1, j-1, and j+1 are all within the bounds of your array.

It should also be noted that while this approach accomplishes what you're trying to accomplish in a very few number of lines, it's far less readable. As such, this approach should be accompanied with very descriptive comments. Moreover, this approach (or any other method) would be best wrapped in an appropriately named function (such as checkNeighbors).

nhgrif
  • 61,578
  • 25
  • 134
  • 173