遍历if语句中的数组

时间:2020-10-06 19:50:02

标签: java arrays

我正在使用可自定义的规则来构建生活游戏。我正在从函数中接收数字数组,并且需要遍历该数组以获取数字集合。我需要在不知道数组长度的情况下将这些数字添加到if语句中,以更新生活游戏的规则。这是代码示例:

if(nAlive < 2)
  next[i][j] = false;
else if(nAlive == 2 || nAlive == 3)
  next[i][j] = true;
else
  next[i][j] = false;

我需要的是(这是伪代码):

if(nAlive == surviving[0] || nAlive == surviving[1] || ... nAlive == surviving[n])
  next[i][j] = true;
else
  next[i][j] = false;

3 个答案:

答案 0 :(得分:1)

答案是:

if(alive[i][j])
                {
                    next[i][j] = false;
                    for (int x = 0; x < surviving.length; x++) {
                        if (surviving[x] == nAlive)
                            next[i][j] = true;
                    }
                }

答案 1 :(得分:1)

尝试一下:

next[i][j] = Arrays.stream(surviving).anyMatch(s == nAlive);

答案 2 :(得分:1)

我的建议是以另一种方式按对象包装此矩阵:

public GameOfLife {
    private Collection<Collection<int>> alive;
    private int numberOfCorrectValues;

    public void addNewValue(int rowIdx, int colIdx, in value){
        if(isMakeTheRules(alive.get(rowIdx).get(colIdx)) and numberOfCorrectValues > 0) numberOfCorrectValues--;
        if((value) isMakeTheRules) numberOfCorrectValues++;
        setAliveWithNewValue(int rowIdx, int colIdx, in value);

    public boolean isTheMatrixMakeTheRules(){
        return numberOfCorrectValues > 0;
    }
}

setAliveWithNewValue 更改集合中的值时(应隐含),而 isMakeTheRules 是每一项检查的方法。

想法是每次保存矩阵的状态并计算一次(仅一次)的大数,并将复杂度从 O(n)降低到 O(1) >

相关问题