override public ILifeBoard NextGeneration(ILifeBoard initial) { if (initial == null) { throw new ArgumentNullException(nameof(initial)); } initial.GenerationCount++; ILifeBoard newCells = initial.GetCellMatrix(initial.RowCount, initial.ColumnCount, initial.GenerationCount); for (int i = 0; i < initial.RowCount; i++) { for (int j = 0; j < initial.ColumnCount; j++) { int countNeighbors = CountNeighbors(initial, i, j); newCells[i, j] = initial[i, j] ? (countNeighbors == 2 || countNeighbors == 3) : (countNeighbors == 3); } } return(newCells); }
override public ILifeBoard SetInitialCells(params string[] initialRows) { if (initialRows.Length == 0) { throw new ArgumentOutOfRangeException(nameof(initialRows)); } if (initialRows.Any(l => l == null)) { throw new ArgumentOutOfRangeException(nameof(initialRows)); } int rowCount = initialRows.Length; int colCount = initialRows.Max(l => l.Length); if (colCount == 0) { throw new ArgumentOutOfRangeException(nameof(initialRows)); } if (rowCount > GetMaxRows() || colCount > GetMaxColumns()) { throw new ArgumentOutOfRangeException(nameof(initialRows)); } ILifeBoard cells = GetCellMatrix(rowCount, colCount, 0); for (int r = 0; r < rowCount; r++) { var l = initialRows[r]; if (l.Length < colCount) { l = l + new string('0', colCount - l.Length); } for (int c = 0; c < colCount; c++) { cells[r, c] = l[c] == '1' || l[c] == 'X'; } } return(cells); }
virtual protected int CountNeighbors(ILifeBoard cellValues, int i, int j) { // wrap to previous row int prevRow = i == 0 ? (cellValues.RowCount - 1) : (i - 1); int prevCol = j == 0 ? (cellValues.ColumnCount - 1) : (j - 1); int nextRow = i == (cellValues.RowCount - 1) ? 0 : (i + 1); int nextCol = j == (cellValues.ColumnCount - 1) ? 0 : (j + 1); int count = 0; count = (cellValues[prevRow, prevCol] ? 1 : 0) + (cellValues[prevRow, j] ? 1 : 0) + (cellValues[prevRow, nextCol] ? 1 : 0) + (cellValues[i, prevCol] ? 1 : 0) + (cellValues[i, nextCol] ? 1 : 0) + (cellValues[nextRow, prevCol] ? 1 : 0) + (cellValues[nextRow, j] ? 1 : 0) + (cellValues[nextRow, nextCol] ? 1 : 0); return(count); }
public ClassicLifeGameAlgorithm(ILifeBoard board) { _board = board; }
abstract public ILifeBoard NextGeneration(ILifeBoard initial);
public ClassicAlgorithm(ILifeBoard board) { _board = board; }