我到处都在寻找这个问题,有一些关于这个问题的答案,但是没有一个我真正理解/不适合我的。
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.
所以我的问题是在包含*或O的2d数组中检查8个邻居。
So my problem is to check for 8 neighbors in an 2d array containing chars, either * or O.
代码:
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++; }对所有8个邻居来说,这都是可行的,但是我不高兴
Etc for all the 8 neighbours, this works, but I'm not happy with the solution.
isAlive()是一个简单的函数,用于确定坐标是*还是O。
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?
谢谢
推荐答案for(int i=-1, i<=1; ++i) { for(int j=-1; j<=1; ++j { if((i || j) && isAlive(g,row+i,column+j)) { aliveCounter++; } } }
此方法假定 i-1 , i + 1 , j-1 和 j + 1 都是在数组的边界之内。
This method assumes that i-1, i+1, j-1, and j+1 are all within the bounds of your array.
还应该注意的是,尽管这种方法可以在很少的几行中完成您要完成的工作,但要少得多因此,此方法应带有描述性很强的注释。最好将ach(或任何其他方法)包装在适当命名的函数中(例如 checkNeighbors )。
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).