英文:
Iterating over an array inside an if statement
问题
我正在构建具有可定制规则的生命游戏。我从函数中收到一个数字数组,需要遍历该数组以获取一组数字。我需要这些数字添加到一个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;
英文:
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 < 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
得分: 1
答案是:
if alive[i][j]:
next[i][j] = False
for x in range(len(surviving)):
if surviving[x] == nAlive:
next[i][j] = True
英文:
The Answer is:
if(alive[i][j])
{
next[i][j] = false;
for (int x = 0; x < surviving.length; x++) {
if (surviving[x] == nAlive)
next[i][j] = true;
}
}
答案2
得分: 1
尝试一下:
next[i][j] = Arrays.stream(surviving).anyMatch(s == nAlive);
英文:
Try this:
next[i][j] = Arrays.stream(surviving).anyMatch(s == nAlive);
答案3
得分: 1
我的建议是按以下方式将这个矩阵封装为对象:
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
是检查每个条目的方法。
这个想法是每次保存矩阵的状态,只计算一次大的条件语句,将复杂度从O(n) 降低到 O(1)。
英文:
My suggestion is wrap this matrix by object in the next way:
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;
}
}
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论