Sudoku: Difference between revisions

Content deleted Content added
No edit summary
Updated D version
Line 1,595:
{{trans|C++}}
<lang d>import std.stdio, std.range, std.string, std.algorithm, std.array;
 
enum int side = 9; // Sudoku grid side
alias immutable(char) TableItem; // Statically in '0'...'9'
alias TableItem[side ^^ 2] SudokuTable;
 
 
SudokuTable sudokuSolver(const ref SudokuTable problem)
in {
Line 1,608:
} body {
uint[side ^^ 2] grid = array(map!q{ a - '0' }(problem[]));
 
bool checkValidity(in int val, in int x, in int y) nothrow {
foreach (i; 0 .. side)
if (grid[y*side + i] == val || grid[i*side + x] == val)
return false;
 
immutable int startX = (x / 3) * 3;
immutable int startY = (y / 3) * 3;
Line 1,622:
return true;
}
 
static class FinishedSudokuException: Exception {
this(string msg) {
Line 1,628:
}
}
 
void placeNumber(in int pos) {
if (pos == side ^^ 2)
Line 1,636:
return;
}
 
foreach (n; 1 .. side+1)
if (checkValidity(n, pos % side, pos / side)) {
Line 1,644:
}
}
 
try {
placeNumber(0);
Line 1,664:
} body {
string result;
 
foreach (i; 0 .. side) {
foreach (j; 0 .. side) {
Line 1,676:
result ~= "------+-------+------\n";
}
 
return result;
}
 
 
void main() {
constimmutable SudokuTable problem =
"850002400" ~
"720000009" ~
Line 1,693 ⟶ 1,692:
"000036040";
writeln(formatSudoku(problem));
 
constimmutable solution = sudokuSolver(problem);
if (solution[0] == TableItem.init)
writeln("Unsolvable!");