gpt4 book ai didi

java - 二维数组 - 计算邻居算法时出错(康威的生命游戏)

转载 作者:行者123 更新时间:2023-11-29 03:48:47 25 4
gpt4 key购买 nike

我在使用 Conways 生命游戏时遇到问题,特别是使用 2D 整数数组来计算 2D boolean 数组中真值“邻居”的数量(为简单起见,所有数组都缩小为 10x10)。

我正在使用以下算法计算二维 boolean 数组中相邻单元格的数量;

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("");
}

我用以下初始值(* = true boolean 值)测试了算法;

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

本来应该是预期的结果;

. . 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?

关于java - 二维数组 - 计算邻居算法时出错(康威的生命游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9690613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com