java - 康威的生命游戏——细胞在不该死的时候死了? ( java )

标签 java algorithm debugging if-statement multidimensional-array

我正在尝试编写一个非常基本的康威生命游戏版本。我的程序几乎可以正常工作,但是 1(代表活细胞)即使有两三个活的邻居也会继续死亡。这很奇怪,因为信号灯有效,但当我尝试信标模式时,它不再有效。

这是一个维基百科链接,其中包含我正在谈论的模式。 http://en.wikipedia.org/wiki/Conway 's_Game_of_Life。

这是我的代码:

public class GameofLife {
public static void main(String[] args){
    int [][] array = new int [12][12];
    array[8][8]=1;
    array[8][9]=1;
    array[8][7]=1;
    int [][] end = new int [12][12];
    printArray(array);
    System.out.println("");
    System.out.println("");
    int a=0;
    while(a<30){
    for(int i=1; i<=10; i++)
    {
        for(int j=1; j<=10; j++)
        {
            int counter = surround(array,i,j);
            if(array[i][j]==1 && counter<2)
            {
                end[i][j]=0;
            }
            if(array[i][j]==1 && counter==2)
            {
                array[i][j]=1;
            }
            if(array[i][j]==1 && counter>4)
            {
                end[i][j]=0;
            }
            if(array[i][j]==0 && counter==3)
            {
                end[i][j]=1;
            }
            if(array[i][j]==1 && counter==3)
            {
                end[i][j]=1;
            }
        }
    }
    printArray(end);    
    a++;
    for(int i=0; i<12; i++)
    {
        for(int j=0; j<12; j++)
        {
            array[i][j]=end[i][j];
            end[i][j]=0;
        }
    }
    System.out.println("");
    System.out.println("");
    }

    public static int surround(int[][] initial, int i, int j){
    int[][] surrounding = {{initial[i-1][j-1],initial[i-1][j],initial[i-1][j+1]},
            {initial[i][j-1],initial[i][j],initial[i][j+1]},
            {initial[i+1][j-1],initial[i+1][j],initial[i+1][j+1]}};
    int counter = 0;
    for(int a=0; a<=2; a++)
    {
        for(int b=0; b<=2; b++)
        {
            if(surrounding[a][b]==1)
            {
                counter ++;
            }
        }
    }
    return counter;
}
public static void printArray(int[][] input)
{
    for(int x =0; x<input.length; x++)
    {
        for(int y=0; y< input[0].length; y++)
        {
            System.out.print(input[x][y]);
        }
        System.out.println("");
    }
}

感谢您的帮助!

最佳答案

这里的逻辑:

for(int a=0; a<=2; a++)
{
    for(int b=0; b<=2; b++)
    {
        if(surrounding[a][b]==1)
        {
            counter ++;
        }
    }
}

有点错误 - 您不需要计算单元格本身,因此需要在 a == 1 && b == 1 时跳过。

...当然还有@Blorgbeard 的评论:-)

关于java - 康威的生命游戏——细胞在不该死的时候死了? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30472729/

相关文章:

java - 可以在 VB.net 程序中使用 Java 库吗?

java - 使用 Java 的 Integer 对象?

c++ - Windows 调试器上的 VS Code 无法与 freopen 一起使用

c++ - gprof 和可执行文件的参数

c - 使用 GDB : I crash (segfault). 我怎样才能看到导致它的代码行?

java - 具有小输入集的 java 中的堆栈溢出错误

java - 如何获得范围内为负数的随机数?

javascript - 如何在 2D 中找到给定 A、B 坐标的平行线

python - 如何有效地左外连接两个排序列表

java - 连接到数据库的速度提高两倍还是连接一次并存储在本地?