public SolverResult TryToSolveOneCell(Grid grid, PencilMarks pencilMarks) { foreach (var column in grid.Columns()) { var digitsToFillIn = grid.AllowedDigits .Where(digit => column.DoesNotContain(digit)); foreach (var digit in digitsToFillIn) { var possibleRows = column.EmptyRows() .Where(rowNumber => pencilMarks.HasMark(column.ColumnNumber, rowNumber, digit)); switch (possibleRows.Count()) { case 0: throw new Exception("Grid can't be solved"); case 1: var newCell = new Cell(column.ColumnNumber, possibleRows.First()); var updatedGrid = grid.FillInSquare(column.ColumnNumber, possibleRows.First(), digit); return(SolverResult.Success(updatedGrid, newCell, $"This is the only cell in this column where {digit} can go.")); default: break; } } } return(SolverResult.Failed(grid)); }
internal bool DoesNotContain(PencilMarks pencilMarks, char digit) { for (int row = 0; row < 9; row++) { if (pencilMarks.HasMark(ColumnNumber, row, digit)) { return(false); } } return(true); }
internal bool DoesNotContain(PencilMarks pencilMarks, char digit) { for (int columnNumber = 0; columnNumber < 9; columnNumber++) { if (pencilMarks.HasMark(columnNumber, RowNumber, digit)) { return(false); } } return(true); }
internal bool DoesNotContain(PencilMarks pencilMarks, char digit) { for (int column = 0; column < 3; column++) { for (int row = 0; row < 3; row++) { if (pencilMarks.HasMark(column + Left, row + Top, digit)) { return(false); } } } return(true); }
public List <string> Evaluate(Grid grid, PencilMarks pencilMarks) { var result = new List <string>(); foreach (var box in grid.Boxes()) { foreach (var digit in grid.AllowedDigits) { if (box.DoesNotContain(digit)) { var columns = new int[3]; var rows = new int[3]; for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { if (pencilMarks.HasMark(box.Left + x, box.Top + y, digit)) { columns[x]++; rows[y]++; } } } if (columns[0] > 0 && columns[1] == 0 && columns[2] == 0) { RemoveFromVerticallyAdjacentBoxes(box, 0, pencilMarks, digit, result); } if (columns[0] == 0 && columns[1] > 0 && columns[2] == 0) { RemoveFromVerticallyAdjacentBoxes(box, 1, pencilMarks, digit, result); } if (columns[0] == 0 && columns[1] == 0 && columns[2] > 0) { RemoveFromVerticallyAdjacentBoxes(box, 2, pencilMarks, digit, result); } if (rows[0] > 0 && rows[1] == 0 && rows[2] == 0) { RemoveFromHorizontallyAdjacentBoxes(box, 0, pencilMarks, digit, result); } if (rows[0] == 0 && rows[1] > 0 && rows[2] == 0) { RemoveFromHorizontallyAdjacentBoxes(box, 1, pencilMarks, digit, result); } if (rows[0] == 0 && rows[1] == 0 && rows[2] > 0) { RemoveFromHorizontallyAdjacentBoxes(box, 2, pencilMarks, digit, result); } } } } return(result); }