我在“人生游戏”示例代码中处理数组时遇到麻烦。
情况:
“生命游戏”是约翰·康威(John Conway)发明的蜂窝自动化技术。它由可以根据数学规则生存/死亡/繁殖的细胞网格组成。使用next()
方法操作此网格中的活细胞和死细胞,其中nPals是网格的初始状态。
题:
我的问题-我知道这很基本-我该如何在next()
上使用nPals
方法进行下一步?
尝试次数:
到目前为止,我的尝试基于以下方面-回顾过去,两者似乎都非常相似。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]
最佳答案
您需要一种方法来执行以下操作:
public void doTurn(int [][]m) {
//manipulate matrix
}
并将其称为每个阶段。