Skip to content

Instantly share code, notes, and snippets.

@cammckinnon
Created February 20, 2013 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cammckinnon/5000257 to your computer and use it in GitHub Desktop.
Save cammckinnon/5000257 to your computer and use it in GitHub Desktop.
public class Untitled {
public static void main(String[] params){
Life life = new Life();
String[][] list = life.readGame();
life.print(list);
System.out.println();
for(int i = 1; i <= 5; i++){
list = life.run(list);
life.print(list);
System.out.println();
}
}
}
class Life {
public String[][] readGame(){
String[][] array = {
{ "-","-", "-", "-", "-", "-","-"},
{ "-","-", "-", "-", "-", "-","-"},
{ "-","-", "-", "x", "-", "-","-"},
{ "-","-", "-", "x", "-", "-","-"},
{ "-","-", "-", "x", "-", "-","-"},
{ "-","-", "-", "-", "-", "-","-"},
{ "-","-", "-", "-", "-", "-","-"}
};
return array;
}
public void print(String[][] array){
for(int x = 0; x < array.length; x++){
for(int y = 0; y < array[x].length; y++){
System.out.print(array[x][y]);
}
System.out.println();
}
}
public String[][] run(String[][] array){
String[][] array_copy = deep_copy(array);
populateCells(array);
System.out.println("Populated:\n");
print(array);
killCells(array, array_copy);
System.out.println("Killed:\n");
print(array);
return array;
}
public int amountOfNeighbors(String[][] array, int x, int y){
int amount = 0;
for(int x1 = -1; x1 <= 1; x1++){
if(x + x1 >= 0 && x + x1 < array.length){
for(int y1 = -1; y1 <= 1; y1++){
if(y + y1 >= 0 && y + y1 < array[x1 + x].length){
if(!(x1 == 0 && y1 == 0) && !array[x1 + x][y1 + y].equals("-")){
amount++;
}
}
}
}
}
return amount;
}
public void populateCells(String[][] array){
int neighbours;
for(int x = 0; x < array.length; x++){
for(int y = 0; y < array[x].length; y++){
neighbours = amountOfNeighbors(array,x,y);
if(neighbours == 3){
array[x][y] = "x";
}
}
}
}
public void killCells(String[][] array, String[][] array_copy){
int neighbours;
for(int x = 0; x < array.length; x++){
for(int y = 0; y < array[x].length; y++){
neighbours = amountOfNeighbors(array_copy,x,y);
if(neighbours <= 1 || neighbours >= 4){
array[x][y] = "-";
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment