Anonymous user
Sudoku: Difference between revisions
→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 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)
?
:
}▼
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);
grid[r][c] = i;
if (
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",▼
▲ static void Main(string[] args) {
▲ "040 007 300" }
.Select(r => r.Where(c => c != ' ').Select(c => (int)c - '0').ToArray())
.ToArray()
Range(
.Select(r => Range(0, 9).Select(c => result[r][c]).Fwd(string.Concat))
Write(report);
ReadLine();
}
}
}</lang>▼
▲</lang>
Output
<pre>975342861
|