遍历数组在 if 语句内部。

go评论61阅读模式

Iterating over an array inside an if statement

问题

``````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;
``````

I am building the game of life with customizable rules. I am receiving an array of numbers from a function and I need to iterate over the array in order to get a collection of numbers. I need those numbers to add to an if statement without knowing the length of the array in order to update the rules for the game of life. Here is the example for the code:

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

What I need is (this is in pseudocode):

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

答案1

``````if alive[i][j]:
next[i][j] = False
for x in range(len(surviving)):
if surviving[x] == nAlive:
next[i][j] = True
``````

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

答案2

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

Try this:

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

答案3

``````public class GameOfLife {
private Collection<Collection<Integer>> alive;
private int numberOfCorrectValues;

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

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

`setAliveWithNewValue`方法改变集合中的值时（你需要实现它），而`isMakeTheRules`是检查每个条目的方法。

My suggestion is wrap this matrix by object in the next way:

``````public GameOfLife {
private Collection&lt;Collection&lt;int&gt;&gt; alive;
private int numberOfCorrectValues;

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

public boolean isTheMatrixMakeTheRules(){
return numberOfCorrectValues &gt; 0;
}
}
``````

when setAliveWithNewValue is change the value in the collection (you should impl it), and isMakeTheRules is method that check per one entry. <br>

the idea is to save the state of the matrix every time and to calculate the big if only once and reduce the complexity from O(n) to O(1)

• 本文由 发表于 2020年10月7日 03:50:02
• 转载请务必保留本文链接：https://go.coder-hub.com/64232880.html
• arrays
• java

go 53

go 55

go 71

go 61