【问题标题】:Cheking the surrounding indexes around an index in 2d matrix检查二维矩阵中索引周围的索引
【发布时间】:2012-11-23 23:18:04
【问题描述】:

我正在开发 Conway 的生命游戏程序,我正处于死/活细胞检查它周围的邻居并计算它周围的活邻居的数量的地步。现在,我正在检查 [0][0]。我遇到的问题是正在检查 [0][0] 以及周围的索引。我想如果我输入“if (k!=o && l!=p)”,它会排除 [0][0],但它没有。

public class Life {

public static void main(String[] args)
{
    int N = 5;
    boolean[][] b = new boolean[N][N];
    double cellmaker = Math.random();

    int i = 0;
    int j = 0;


    int o=0;
    int p=0;
    int livecnt = 0; //keeps track of the alive cells surrounding cell

     System.out.println("First Generation:");
     // Makes the first batch of cells
     for ( i = 0; i < N ; i++)
     {

         for ( j = 0; j< N; j++)
         {
              cellmaker = Math.random();


             if (cellmaker > 0.5) // * = alive; - = dead
             {
                 b[i][j]=true;

                 System.out.print( "* ");

             }


             if (cellmaker < 0.5)
            { b[i][j] = false;


             System.out.print("- ");

            }

         }
         System.out.println();
     }       

     // Checks for the amount of "*" surrounding (o,p)
     for (int k=(o-1); k <= o+1; k++ )
        {

            for (int l =(p-1); l <=p+1; l++)
            {
                 if ( k >= 0 && k < N && l >= 0 && l < N) //for the border indexes.
                 { 
                     //if (k!=o && l!=p)
                    {
                        if (b[k][l] == true)
                            {

                                livecnt++;

                            }
                    }

                 }

            }
        } 
    System.out.println(livecnt++);
}

}

【问题讨论】:

  • 建议不要将变量声明为l。很容易被误认为1。就像你现在想的那样,哪个是one,哪个是L?请为您的变量选择一个更好的名称。

标签: java for-loop nested-loops conways-game-of-life


【解决方案1】:

你想检查 (o,p) 的周围,试试这样:

if (!(k== o && l==p))

代替:

if (k!=o && l!=p)

因为在上述条件下,您没有检查坐标 (k,p-1)、(k,p+1)、(k-1,p) 和 (k+1,p)

【讨论】:

    【解决方案2】:

    您的代码几乎是正确的。你只需要改变

    if (k!=o && l!=p)
    

    进入

    if (k!=o || l!=p)
    

    如果坐标(k,l) 不等于(o,p),您只想计算一个字段 换句话说: !(k==o && l==p) 记住(k!=o || l!=p) 等于!(k==o &amp;&amp; l==p) 根据De Morgan's laws.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      相关资源
      最近更新 更多