繁体   English   中英

2D阵列 - 计算邻居算法的错误(康威的生命游戏)

[英]2D Arrays - Error with counting neighbours algorithm (Conway's Game of Life)

我遇到了Conways Game of Life的问题,特别是使用2D整数数组来计算2D布尔数组中真值“邻居”的数量(为简单起见,所有数组都缩小到10x10)。

我使用以下算法来计算2D布尔数组中相邻单元的数量;

public static int neighbourCount(boolean[][] inputArray, int x, int y)
{
    // X and Y co-ordinates for all spots around current point
    int[] xVals = {x - 1,   x - 1,  x - 1,  x,      x,      x + 1,  x + 1,  x + 1};
    int[] yVals = {y - 1,   y,      y + 1,  y - 1,  y + 1,  y - 1,  y,      y + 1};

    int nCount = 0;

    // Count neighbours algorithm
    for (int i = 0; i < 8; i++)
    {
        if (xVals[i] > 0 && yVals[i] > 0 && xVals[i] < 10 && yVals[i] < 10)
        {
            if (inputArray[(xVals[i])][(yVals[i])])
            {
                nCount++;
            }
        }
    }
    return nCount;
}

我专门用这个算法来防止越界异常。

我使用以下算法打印出值;

    // Print countNeighbours Algorithm
    for (int i=0; i < 10; i++)
    {
        for (int j=0; j < 10; j++)
        {
            countNeighbours[i][j] = neighbourCount(gameBoard, i, j);
            System.out.print(" " + countNeighbours[i][j]);
        }

    System.out.println("");
    }

我用以下初始值测试了算法(* =真布尔值);

. . . . * . . . . .
. . . * * * . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .

预期的结果应该是;

. . 1 3 3 3 1 . . .
. . 1 2 3 2 1 . . .
. . 1 2 3 2 1 . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .

给出的结果是;

. . 1 2 3 2 1 . . .
. . 1 1 2 1 1 . . .
. . 1 2 3 2 1 . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .

我曾考虑使用一个替代算法,使用一个稍微大一点的数组来防止越界异常,但它包含许多if语句,看起来非常混乱。

任何有用的洞察这个问题将非常感谢,并提前感谢。

当测试索引在边界内时,你应该测试> = 0,而不是> 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM