Sudoku: Difference between revisions

359 bytes removed ,  2 years ago
→‎Functional Recursive Backtrack Solution: Made more fluent and functional
m (→‎Recursive Backtrack Solution: Changed C# Version this works with)
(→‎Functional Recursive Backtrack Solution: Made more fluent and functional)
Line 1,829:
<!-- By Martin Freedman, 20/11/2021 -->
<lang csharp>using System.Linq;
using System.Linq;
using static System.Linq.Enumerable;
using static System.Console;
Line 1,836 ⟶ 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) => values.Where(c => c != 0).Unique();
 
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)
Line 1,851 ⟶ 1,850:
GetBox(grid, row, col).IsUnequal();
 
private static (int, int) NextEmptyCell(this int[][] grid, int r, int c) {=>
while (r < 9 && grid[r][c] != 0) {
? NextEmptyCell(grid, c == 8 ? r + 1 : r, ++c % 9;)
: (r +=, c == 0 ? 1 : 0);
}
return (r, c);
}
 
private static (bool, int[][]) Solve(this int[][] grid, int row, int col) {
var (r, c) = grid.NextEmptyCell(row, col);
 
if (r == 9) //success
return (true, grid);
 
forforeach (var i =in Range(1; i <= ,9; i++)) {
grid[r][c] = i;
if (!grid.Constraints(r, c)) {
continuevar (success, g) = grid.Solve(r, c);
var (success, g) = grid.Solveif (r, csuccess);
if return (!successtrue, g);
continue;}
else}
return (true, g);
}
grid[r][c] = 0; //backtrack
return (false, grid);
}
 
private static U Fwd<T, U>(this T t, Func<T, U> func) => func(t);
static void Main(string[] args) {
var challenge = new string[]{ "970 340 060",
"861 750 000",
"324 168 957",
"219 584 673",
"487 236 519",
"653 971 284",
"738 425 196",
"002 010 048",
"040 007 300" };
 
static void Main(string[] args) {
var input = challenge
var challengereport = new string[]{ "970 340 060",
} "970 340 060",
"861 750 000",
"324 168 957",
"219 584 673",
"487 236 519",
"653 971 284",
"738 425 196",
"002 010 048",
"040 007 300" }
.Select(r => r.Where(c => c != ' ').Select(c => (int)c - '0').ToArray())
.ToArray();
return .Solve(true0, g0); switch {
 
var report = input.Solve (0true, 0var result) switch {=>
Range(true0, var result9) =>
.Select(r => Range(0, 9).Select(c => result[r][c]).Fwd(string.Concat))
.Select(r => Range(0, 9) .SelectFwd(cs => result[r][c]).Fwd(string.ConcatJoin('\n', s)),
.Fwd(s_, _) => string.Join('\n', s)),
(_, _) => "No Solution\n"
"No Solution\n"};
};
Write(report);
ReadLine();
}
}
}</lang>
}
</lang>
Output
<pre>975342861