Sudoku: Difference between revisions
Content added Content deleted
(New D entry that solves far more Sudokus) |
(Stronger types for D entry) |
||
Line 1,499: | Line 1,499: | ||
<lang d>import std.stdio, std.range, std.string, std.algorithm, std.array; |
<lang d>import std.stdio, std.range, std.string, std.algorithm, std.array; |
||
⚫ | |||
⚫ | |||
alias immutable(char) TableItem; // Statically in '0'...'9' |
|||
alias TableItem[side ^^ 2] SudokuTable; |
|||
⚫ | |||
in { |
in { |
||
⚫ | |||
⚫ | |||
assert(problem.walkLength == side ^^ 2); |
|||
⚫ | |||
} body { |
} body { |
||
⚫ | |||
enum int side = 9; |
|||
⚫ | |||
bool checkValidity(in int val, in int x, in int y) nothrow { |
bool checkValidity(in int val, in int x, in int y) nothrow { |
||
Line 1,520: | Line 1,522: | ||
return false; |
return false; |
||
return true; |
return true; |
||
} |
|||
static class FinishedSudokuException: Exception { |
|||
this(string msg) { |
|||
super(msg); |
|||
} |
|||
} |
} |
||
void placeNumber(in int pos) { |
void placeNumber(in int pos) { |
||
if (pos == side ^^ 2) |
if (pos == side ^^ 2) |
||
throw new |
throw new FinishedSudokuException("Finished!"); |
||
if (grid[pos] > 0) { |
if (grid[pos] > 0) { |
||
placeNumber(pos + 1); |
placeNumber(pos + 1); |
||
Line 1,540: | Line 1,548: | ||
try { |
try { |
||
placeNumber(0); |
placeNumber(0); |
||
return |
return typeof(return).init; |
||
} catch ( |
} catch (FinishedSudokuException ex) { |
||
//auto r = map!q{ cast(TableItem)(a + '0') }(grid[]); |
|||
auto r = map!q{ cast(char)(a + '0') }(grid[]); |
|||
SudokuTable result = array(r).idup; |
|||
return result; |
|||
} |
|||
} |
} |
||
string formatSudoku( |
string formatSudoku(const ref SudokuTable sudo) |
||
in { |
in { |
||
⚫ | |||
enum int side = 9; // dupe |
|||
assert(sudo.walkLength == side ^^ 2); |
|||
⚫ | |||
} body { |
} body { |
||
enum int side = 9; |
|||
string result; |
string result; |
||
Line 1,572: | Line 1,581: | ||
void main() { |
void main() { |
||
const problem = |
const SudokuTable problem = |
||
"850002400" ~ |
|||
"720000009" ~ |
|||
"004000000" ~ |
|||
"000107002" ~ |
|||
"305000900" ~ |
|||
"040000000" ~ |
|||
"000080070" ~ |
|||
"017000000" ~ |
|||
"000036040"; |
|||
writeln(formatSudoku(problem)); |
writeln(formatSudoku(problem)); |
||
const solution = sudokuSolver(problem); |
const solution = sudokuSolver(problem); |
||
if (solution. |
if (solution[0] == TableItem.init) |
||
writeln("Unsolvable!"); |
writeln("Unsolvable!"); |
||
else |
else |