Jump to content

Sudoku: Difference between revisions

(→‎Recursive Backtrack Solution: More fluent syntax)
Line 1,835:
namespace Sudoku {
static class Program {
private static bool Unique(this IEnumerable<int> values) => values.Distinct().Count() == values.Count();
private static bool IsUnequal(this IEnumerable<int> values) => Unique(values.Where(c => c != 0).Unique();
 
private static int RowCol(int rc) => rc <= 2 ? 0 : rc <= 5 ? 3 : 6;
Line 1,844:
select grid[r][c];
 
private static bool Constraints(this int[][] grid, int row, int col) =>
IsUnequal(Range(0, 9).Select(c => grid[row][c]).IsUnequal() &&
IsUnequal(Range(0, 9).Select(r => grid[r][col]).IsUnequal() &&
IsUnequal(GetBox(grid, row, col).IsUnequal();
 
private static (int, int) NextEmptyCell(this int[][] grid, int r, int c) {
while (r < 9 && grid[r][c] != 0) {
c = ++c % 9;
Line 1,857:
}
 
private static (bool, int[][]) Solve(this int[][] grid, int row, int col) {
var (r, c) = grid.NextEmptyCell(grid, row, col);
if (r == 9) //success
Line 1,865:
for (var i = 1; i <= 9; i++) {
grid[r][c] = i;
if (!grid.Constraints(grid, r, c))
continue;
var (success, g) = grid.Solve(grid, r, c);
if (!success)
continue;
Line 1,893:
.ToArray();
 
var (success, result) = input.Solve(input, 0, 0);
 
if (success)
Line 1,907:
}
}
}
}</lang>
Output
<pre>975342861
Cookies help us deliver our services. By using our services, you agree to our use of cookies.