Anonymous user
Sudoku: Difference between revisions
m
→Functional Recursive Backtrack Solution
m (→Functional Recursive Backtrack Solution: No need to state C# version) |
|||
Line 1,830:
<lang csharp>using System.Linq;
using static System.Linq.Enumerable;
using static System.Console;▼
using System.Collections.Generic;
using System;
namespace Sudoku {
internal static class
private static bool Unique(this IEnumerable<int> values) => values.Distinct().Count() == values.Count();
private static bool IsUnequal(this IEnumerable<int> values) => values.Where(c => c != 0).Unique();
Line 1,849:
GetBox(grid, row, col).IsUnequal();
private static
.Union(Range(0, 9).Select(r => grid[r][col]).Distinct())
.Union(GetBox(grid, row, col).Distinct())
.Where(c => c != 0);
private static IEnumerable<(int, int)> SortedCells(this int[][] grid) =>
from row in Range(0, 9)
from col in Range(0, 9)
let cell = (count: Hints(grid, row, col).Count(), cell: (row, col))
orderby cell.count descending
select cell.cell;
private static bool Solve(this int[][] grid, List<(int,int)> cells, int idx) {
if (idx == 81)
return true;
var (r, c) = cells[idx];
if (grid[r][c] != 0)
return grid.Solve(
foreach (var i in Range(1, 9)) {
grid[r][c] = i;
if (grid.Constraints(r, c) && grid.Solve(
return true;
return false;
}
private static int[][] Parse(string input) =>
input
.Select((c, i) => (index: i, val: int.Parse(c.ToString())))
Line 1,871 ⟶ 1,885:
.ToArray();
public static string AsString(this int[][] grid) =>
public static int[][] Run(string input) {
var grid = Parse(input);
return grid.Solve(grid.SortedCells().ToList(), 0) ? grid : new int[][]{ Array.Empty<int>() };
}
}
}</lang>▼
Usage
<lang csharp>
▲using static System.Console;
namespace Sudoku {
static class Program {
static void Main(string[] args) {
var watch = new System.Diagnostics.Stopwatch();
var puzzle = "000028000800010000000000700000600403200004000100700000030400500000000010060000000";
WriteLine($"Completed in {watch.ElapsedMilliseconds} ms");
▲ ? string.Join('\n', grid.Select(row=>string.Concat(row)))
Read();
}</lang>
▲</lang>
Output
<pre>
697328105
800517234
354906700
579682403
286134957
103759628
738460509
425093816
961875302
Completed in 431 ms
</pre>
===“Automatic” Solution===
|