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.

73 lines
2.8 KiB

package de.hsfulda.pmuw.oop;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CellCreator {
/** one alive to X dead */
private static final int ALIVE_CELLS_RATIO = 30;
private static final int BOARD_SIZE = 500;
public static List<Boolean> aliveList = new Random().ints(0, ALIVE_CELLS_RATIO).limit(BOARD_SIZE * BOARD_SIZE)
.mapToObj(Integer::valueOf).map(i -> Boolean.valueOf(i == 0)).collect(Collectors.toList());
int calculateNeighbourIndex(List<CgolCell> allCells, CgolCell cgolCell, NeighborPosition neighborPosition) {
int row = cgolCell.row;
int column = cgolCell.column;
int size = allCells.size();
int index = neighborPosition.getIndex(row, column, BOARD_SIZE);
int finalIndex = (index + size) % size;
return finalIndex;
}
protected void createCells(Collection<CgolCell> activeCells, boolean isOptimized) {
StateChangeListener<CgolCell> changeListener = getChangeListener(activeCells, isOptimized);
List<CgolCell> allCells = createCells(changeListener);
constructGameField(activeCells, isOptimized, allCells);
System.out.println(String.format("active cells: %7s", activeCells.size()));
System.out.println(String.format("alive cells : %7s", allCells.stream().filter(CgolCell::isAlive).count()));
}
private StateChangeListener<CgolCell> getChangeListener(Collection<CgolCell> activeCells, boolean isOptimized) {
StateChangeListener<CgolCell> changeListener = isOptimized ? nc -> activeCells.add(nc) : nc -> {
;
};
return changeListener;
}
private List<CgolCell> createCells(StateChangeListener<CgolCell> changeListener) {
Iterator<Boolean> iterator = aliveList.iterator();
List<CgolCell> allCells = new ArrayList<>();
for (int row = 0; row < BOARD_SIZE; row++)
for (int col = 0; col < BOARD_SIZE; col++)
allCells.add(new CgolCell(row, col, iterator.next(), changeListener));
System.out.println(String.format("cells created: %7s", allCells.size()));
return allCells;
}
private void constructGameField(Collection<CgolCell> activeCells, boolean isOptimized, List<CgolCell> allCells) {
for (CgolCell cgolCell : allCells) {
Set<CgolCell> neighbors = Stream.of(NeighborPosition.values())
.map(np -> calculateNeighbourIndex(allCells, cgolCell, np)).map(allCells::get).collect(Collectors.toSet());
cgolCell.setNeighbors(neighbors);
if (cgolCell.isAlive()) {
if (isOptimized) {
activeCells.add(cgolCell);
activeCells.addAll(neighbors);
}
}
}
if (!isOptimized) {
activeCells.addAll(allCells);
}
}
}