【发布时间】:2023-04-01 06:10:02
【问题描述】:
我在此 Game of Life 示例代码中处理数组时遇到问题。
情况:
“生命游戏”是约翰康威发明的一种细胞自动化。它由一个网格组成,可以根据数学规则生存/死亡/繁殖。该网格中的活细胞和死细胞使用next() 方法进行操作,nPals 是网格的初始状态。
问题:
我的问题 - 我知道这是相当基本的问题 - 是如何使用 nPals 上的 next() 方法给我下一阶段?
尝试:
到目前为止,我的尝试都遵循以下思路 - 回顾过去,这两者似乎都非常相似。
nPals.next();int newNPALS[][] = nPals.next(); // and then printing the array newNPALS
任何想法将不胜感激!
代码:
public class GameOfLife {
static int nPals[][] = {
{0,0,0,0,0,0,0},
{0,1,2,3,2,1,0},
{0,2,102,104,102,2,0},
{0,3,104,8,104,3,0},
{0,2,102,104,102,2,0},
{0,1,2,3,2,1,0},
{0,0,0,0,0,0,0}
};
public static void main(String[] args) {
//Initial Stage
System.out.println(" >>First Stage<<");
printMatrix(nPals);
//Second Stage
System.out.println("\n >>Second Stage<<");
printMatrix(nPals);
}//end main
static Stack<Integer>stk=new Stack<Integer>();
static final int LIVE=100;
static final int MAXGRIDSIZE=1024;
public static void next(){
for (int i=0;i<nPals.length;i++){
for(int j=0;j<nPals[i].length;j++){
switch(nPals[i][j]){
case LIVE+0:case LIVE+1:case LIVE+4:
case LIVE+5:case LIVE+6:case LIVE+7:
stk.push(-(i*MAXGRIDSIZE+j)); //death
nPals[i][j]-=LIVE;
break;
case 3:
stk.push(i*MAXGRIDSIZE+j); //life
nPals[i][j]+=LIVE;
break;
}//end switch
}//end for j
}//end for i
while(!stk.isEmpty()){
int k=stk.pop();
if(k>0)inc(k/MAXGRIDSIZE,k%MAXGRIDSIZE);
else{
k=-k;
dec(k/MAXGRIDSIZE,k%MAXGRIDSIZE);
}//end if
}//end while
}//end next
private static void inc(int i, int j) {
}
private static void dec(int i, int j){
if(i!=0){
//3 squares on top
if(j!=0) minus(i-1,j-1);
minus(i-1,j);
if(j!=nPals[i].length-1)minus(i-1,j+1);
}
//2 on either side
if(j!=0)minus(i,j-1);
if(j!=nPals[i].length-1)minus(i,j+1);
if(i!=nPals.length-1){
//3 squares on bottom
if(j!=0)minus(i+1,j-1);
minus(i+1,j);
if(j!=nPals[i].length-1)minus(i+1,j+1);
}
}
private static void minus(int i, int j){
if(nPals[i][j]>0)nPals[i][j]--;
}
private static void plus(int i, int j){
if(nPals[i][j]<=0)nPals[i][j]++;
}
//This is just for explaining printMatrix above, otherwise immaterial
public static <E> void printMatrix(int[][] m){
for(int[] rows:m){
System.out.println(Arrays.toString(rows));
}
}//end printMatrix
}//end GameOfLife
输出:
>>First Stage<<
[0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 2, 1, 0]
[0, 2, 102, 104, 102, 2, 0]
[0, 3, 104, 8, 104, 3, 0]
[0, 2, 102, 104, 102, 2, 0]
[0, 1, 2, 3, 2, 1, 0]
[0, 0, 0, 0, 0, 0, 0]
>>Second Stage<< /* currently unchanged */
[0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 2, 1, 0]
[0, 2, 102, 104, 102, 2, 0]
[0, 3, 104, 8, 104, 3, 0]
[0, 2, 102, 104, 102, 2, 0]
[0, 1, 2, 3, 2, 1, 0]
[0, 0, 0, 0, 0, 0, 0]
【问题讨论】:
-
解释人生游戏。不要指望每个人都知道它是如何工作的
-
GoL 实现的一个常见问题是尝试更新和使用单个数组来获取有关细胞存活的信息。保留两个数组。顺便说一句 - 看起来你真的用
/* fill in code here */指令复制了你的作业。 SO 不是那样工作的。 -
@AndrewThompson:我不明白你评论的后半部分。我并没有试图隐瞒这是学校作业的事实。我只是不想用不一定相关的代码轰炸用户。以供将来参考,什么是更好的代码输入方式?
-
'我只是不想用不一定相关的代码来轰炸用户。”相关的代码就是你的代码已经尝试过了。向我们展示您的尝试。
标签: java arrays methods matrix conways-game-of-life