java - 为什么我返回的计数值错误?

标签 java conways-game-of-life

    public static int countNeighbors(boolean[][] BB, int r, int c) {
    int countalive = 0;
    for (int i = r -1;i<=r+1; i++) {
        for (int j = c -1; j<c+1;j++) {

            if (BB[i][j]) {
                countalive++;

            }

        }
    }
    return countalive;
}

正在读取矩阵。

oooooooo
o###oooo
o####o#o
ooo##o#o
o#o#o##o
oooooooo

我发现有问题,所以我打印了这部分代码。当按规范运行时

countNeighbors(myNewMatrix,1,1)

我得到了 2 的返回值,而实际上它应该是 3。

它正在计算其周围为 True(#) 的图 block 的数量。

这是“人生游戏”作业。

最佳答案

(1,1) 在 (1,2)、(2,1) 和 (2,2) 有 3 个邻居。您的代码在 2 个帐户上是错误的:

  1. 您正在对单元格本身 (1,1) 进行计数。这使得计数 1 过高。介绍一个if以避免计算 (r,c) 位置本身。
  2. 您在 j 中停止得太早了for循环,在到达 c + 1 之前.这使得计数 2 太低(缺少 2 个匹配项)。将条件更改为 j<=c+1 , 与 i 保持一致for循环条件。

两个错误(+1 和 -2)的综合影响解释了为什么您的计数低 1 .

关于java - 为什么我返回的计数值错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25773259/

相关文章:

java - eclipse : Can we make modifications on to the source code while debugging the Application inside Eclipse

java - 扩展类时出错

java - 使用 ArrayDeque 实现缓存

java - JAX-RS 中的异常处理

Haskell parMap 和并行性

java - Maven 测试失败 : Cannot find symbol

java - 康威的生命游戏更新(下一代)

java - 生命游戏问题

javascript - Node JS 将二维数组显示为网格