Anonymous user
Sudoku: Difference between revisions
Changed my →“Amb” Solution: to better and shorter →Recursive Backtrack Solution
m (→{{header|Tailspin}}: handle autotyping of tagged identifiers) |
(Changed my →“Amb” Solution: to better and shorter →Recursive Backtrack Solution) |
||
Line 1,825:
}
}</lang>
===
{{works with|C sharp|C#|7.1}}
<!-- By Martin Freedman,
<lang csharp>using System.Linq;
using static System.Linq.Enumerable;
using static System.Console;
using
namespace Sudoku {
static class Program {
private static bool Unique(IEnumerable<int> values) => values.Distinct().Count() == values.Count();
private static bool IsUnequal(IEnumerable<int> values) => Unique(values.Where(c => c != 0));
private static int RowCol(int rc) => rc <= 2 ? 0 : rc <= 5 ? 3 : 6;
private static IEnumerable<int> GetBox(int[][] grid, int row, int col) =>
from r in Range(RowCol(row), 3)
from c in Range(RowCol(col), 3)
select grid[r][c];
private static bool Constraints(int[][] grid, int row, int col) =>
IsUnequal(Range(0, 9).Select(c => grid[row][c])) &&
IsUnequal(Range(0, 9).Select(r => grid[r][col])) &&
IsUnequal(GetBox(grid, row, col));
private static (int, int) NextEmptyCell(int[][] grid, int r, int c) {
while (r < 9 && grid[r][c] != 0) {
c = ++c % 9;
r = c == 0 ? r + 1 : r;
}
return (r, c);
}
private static (bool, int[][]) Solve(int[][] grid, int row, int col) {
var (r, c) = NextEmptyCell(grid, row, col);
if (r == 9) //success
return (true, grid);
for (var i = 1; i <= 9; i++) {
grid[r][c] = i;
if (!Constraints(grid, r, c))
continue;
var (success, g) = Solve(grid, r, c);
if (!success)
continue;
else
return (true, g);
}
grid[r][c] = 0; //backtrack
return (false, grid);
}
static void Main(string[] args) {
var challenge = new string[]{ "970 340 060",
"861 750 000",
Line 1,850 ⟶ 1,889:
"040 007 300" };
var
.Select(r => r.Where(c => c != ' ').Select(c => (int)c - '0').ToArray())
.ToArray();
var
for (var c = 0; c < 9; c++) {
Write($"{result[r][c]}");
}
Write("\n");
}
else
}
}
Line 1,928 ⟶ 1,919:
146897325
</pre>
===“Automatic” Solution===
|