You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.9 KiB

package de.hsfulda.pmuw.procedural;
import java.util.Calendar;
import java.util.Iterator;
import de.hsfulda.pmuw.oop.CellCreator;
public class CgolBoardProcedural {
/** one alive to X dead */
static final int ALIVE_CELLS_RATIO = 30;
static final int BOARD_SIZE = 500;
private boolean[][] board = new boolean[BOARD_SIZE][BOARD_SIZE];
public void initialize() {
createCells();
System.out.println(String.format("cells created: %7s", BOARD_SIZE*BOARD_SIZE));
System.out.println(String.format("active cells: %7s", BOARD_SIZE*BOARD_SIZE));
System.out.println(String.format("alive cells : %7s", countAliveCells()));
}
private void createCells() {
Iterator<Boolean> iterator = CellCreator.aliveList.iterator();
for (int row = 0; row < board.length; row++)
for (int col = 0; col < board[0].length; col++)
board[row][col] = iterator.next();
}
public void nextGen() {
boolean[][] nextGen = new boolean[BOARD_SIZE][BOARD_SIZE];
for (int row = 0; row < board.length; row++)
for (int col = 0; col < board[0].length; col++)
nextGen[row][col] = newStateOfCell(row, col);
board = nextGen;
}
private boolean newStateOfCell(int row, int col) {
int countAliveNeighbors = countAliveNeighbors(row, col);
return newState(countAliveNeighbors, board[row][col]);
}
private int countAliveNeighbors(int row, int col) {
int aliveNeighbors = 0;
for (int rOffset = -1; rOffset <= 1; rOffset++)
for (int cOffset = -1; cOffset <= 1; cOffset++)
aliveNeighbors += board[(row + rOffset + BOARD_SIZE) % BOARD_SIZE][(col + cOffset + BOARD_SIZE) % BOARD_SIZE]
? 1
: 0;
return aliveNeighbors - (board[row][col] ? 1 : 0);
}
private boolean newState(int aliveNeighbors, boolean isAlive) {
return 3 == aliveNeighbors || (isAlive && 2 == aliveNeighbors);
}
private int countAliveCells() {
int aliveCells = 0;
for (int row = 0; row < board.length; row++)
for (int col = 0; col < board[0].length; col++)
aliveCells += board[row][col] ? 1 : 0;
return aliveCells;
}
public static void main(String[] args) {
long start = Calendar.getInstance().getTimeInMillis();
CgolBoardProcedural cgolBoard = new CgolBoardProcedural();
cgolBoard.initialize();
long end = Calendar.getInstance().getTimeInMillis();
System.out.println(String.format("initializing took: %sms", end - start));
start = Calendar.getInstance().getTimeInMillis();
int iterations = 1000;
for (int i = 0; i < iterations; i++) {
cgolBoard.nextGen();
if (0 == i % 100)
System.out.println(String.format("iteration %6d cells alife: %s , cells active %7s", i, cgolBoard.countAliveCells(),BOARD_SIZE*BOARD_SIZE));
}
end = Calendar.getInstance().getTimeInMillis();
System.out.println(String.format("time spend for %d iterations: %sms\n\n", iterations, end - start));
}
}