检查布尔数组中是否存在元素

时间:2013-05-30 14:40:41

标签: java arrays code-cleanup

我参加了一个编程课程,我正在重新审视我不太正确的旧程序。这是一个生命游戏计划,我有一个关于代码清理的问题。

在检查其邻居的布尔值是true还是false之前,我需要确保数组元素在边界内。我有一个声明来检查firstGen[0][0]的左上角(向上一行,左边一列)是否在边界内。是否有更简单或更优雅的方法来检查元素是否在边界内或将元素检查限制在给定数组的边界而不使用每个&&语句的四个if条件?

请注意,到目前为止我只更改了第一个if语句,因此其他地方可能会出现错误。我也排除了对其他邻居的边界检查。

    public static boolean[][] generation(boolean[][] firstGen)
    {
    int length = firstGen.length;
    boolean[][] newGen = new boolean[length][length];

    for (int j = 0; j < firstGen[0].length; j++)
        { for (int i = 1; i < firstGen.length; i++)
            {
                int count = 0;
                if  ((i-1 >= 0) && (i-1 < length) && (j-1 >= 0) && (j-1 < length)) //top-left element exists
                    { if  (newGen[i-1][j-1] == true) count++; } //increment `count` if top-left element is true

                if ((newGen[i][j] == false) && (count == 3)) newGen[i][j] = true;
                else if ((newGen[i][j] == true) && (count == 1)) newGen[i][j] = false;
                else if ((newGen[i][j] == true) && (count > 3)) newGen[i][j] = false;
                else break;
             }
        }
        return newGen;
      }

2 个答案:

答案 0 :(得分:3)

如果ij在界限范围内,那么您确定i - 1 < lengthj - 1 < length都是正确的。

此外:

  • i - 1 >= 0可以写成i > 0
  • if (condition == true)可以重写if (cond)

所以你可以替换:

if  ((i-1 >= 0) && (i-1 < length) && (j-1 >= 0) && (j-1 < length)) //top-left element exists
    { if  (newGen[i-1][j-1] == true) count++; } //increment `count` if top-left element is true

由:

//increment `count` if top-left element is true
if  (i > 0 && j > 0 && newGen[i-1][j-1]) count++;

答案 1 :(得分:1)

这是我能想到的最好的方法来检查它是否超出范围,但是一般的替代方法,以及我认为给生活游戏更令人兴奋的结果等程序增加周期性边界的方法。基本上这意味着如果你走出一条边,你最终会走到另一边(就像在pac-man中)。这听起来很复杂,但实际上只需要%函数,它返回给定的两个数字之间的余数。

所以:

27 % 5 = 2;

因此,为了添加周期性边界,您可以像这样更新x和y位置:

x = (x + xStep + horizontalSize) % horizontalSize;
y = (y + yStep + verticalSize) % verticalSize;

其中xStep和yStep为+1或-1,具体取决于您要去的方向。 (这适用于for循环)增加大小是为了确保在接近边界时低于零。

然后你永远不必担心凌乱的边境条件,一切都只是重叠。无需检查每个边界。我希望这是有道理的。如果没有,请要求澄清。我已经将它用于随机漫步者程序,但想法是一样的。

相关问题