Keep state the same if it doesn't fall in the following conditions:
- Change to 2 if there are exactly 2 ones in the neighbors
- Change to 3 if there are more than 2 ones in the neighbors
It is also wrapping around so neighbors can be cyclic.
I wrote a basic structure and modularized it to individual functions. I wish to understand better coding techniques and how I can improve.
package code.Misc;
public class changeStateGame {
public static void main(String args[]){
int current[][] = {
{0,0,0,0,0,0,0},
{0,0,0,0,1,0,0},
{0,0,0,1,1,0,0},
{0,0,1,1,0,0,0},
{0,0,0,0,0,0,0}
};
int aux [][] = new int [current.length][current[0].length];
for(int i=0;i<current.length;i++){
for(int j=0;j<current[0].length;j++){
aux[i][j]=0;
}
}
System.out.println("Current State");
printStateGame(current);
System.out.println("Changed State");
printStateGame(changeState(current,aux,0,aux[0].length));
}
public static void printStateGame(int a[][]){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[0].length;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public static int [][] changeState(int c[][],int a[][], int row, int col){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[0].length;j++){
a[i][j]=checkNeighbors(c,i,j);
}
}
return a;
}
public static int checkNeighbors(int a[][],int row,int col){
int neighborCount = 0;
for(int i=row-1;i<row+1;i++){
for(int j=col-1;j<col+1;j++){
if (i < 0)
i = a.length - 1;
if (j < 0)
j = a[0].length - 1;
if (i == a.length)
i = 0;
if (j == a[0].length)
j = 0;
if(i==row){
if(j==col){
continue;
}
}
if(j==col){
if(i==row){
continue;
}
}
neighborCount += checkElement(a[i][j]);
}
}
return modifyElement(a[row][col],neighborCount);
}
public static int checkElement(int a){
if(a==1)
return 1;
else
return 0;
}
public static int modifyElement(int a, int count){
if(count<2){
return a;
}
else if (count == 2){
return 2;
}
else {
return 3;
}
}
}