Sudoku: Difference between revisions
Content deleted Content added
Realize in F# |
|||
Line 5,288: | Line 5,288: | ||
5 9 8 | 7 3 6 | 2 4 1 |
5 9 8 | 7 3 6 | 2 4 1 |
||
</pre> |
</pre> |
||
=={{header|Nim}}== |
|||
{{trans|Kotlin}} |
|||
<lang nim>{.this: self.} |
|||
type |
|||
Sudoku = ref object |
|||
grid : array[81, int] |
|||
solved : bool |
|||
proc `$`(self: Sudoku): string = |
|||
var sb: string = "" |
|||
for i in 0..8: |
|||
for j in 0..8: |
|||
sb &= $grid[i * 9 + j] |
|||
sb &= " " |
|||
if j == 2 or j == 5: sb &= "| " |
|||
sb &= "\n" |
|||
if i == 2 or i == 5: sb &= "------+------+------\n" |
|||
sb |
|||
proc init(self: Sudoku, rows: array[9, string]) = |
|||
for i in 0..8: |
|||
for j in 0..8: |
|||
grid[9 * i + j] = rows[i][j].int - '0'.int |
|||
proc checkValidity(self: Sudoku, v, x, y: int): bool = |
|||
for i in 0..8: |
|||
if grid[y * 9 + i] == v or grid[i * 9 + x] == v: return false |
|||
var startX = (x div 3) * 3 |
|||
var startY = (y div 3) * 3 |
|||
for i in startY..startY + 2: |
|||
for j in startX..startX + 2: |
|||
if grid[i * 9 + j] == v: return false |
|||
result = true |
|||
proc placeNumber(self: Sudoku, pos: int) = |
|||
if solved: return |
|||
if pos == 81: |
|||
solved = true |
|||
return |
|||
if grid[pos] > 0: |
|||
placeNumber(pos + 1) |
|||
return |
|||
for n in 1..9: |
|||
if checkValidity(n, pos mod 9, pos div 9): |
|||
grid[pos] = n |
|||
placeNumber(pos + 1) |
|||
if solved: return |
|||
grid[pos] = 0 |
|||
proc solve(self: Sudoku) = |
|||
echo "Starting grid:\n\n", $self |
|||
placeNumber(0) |
|||
if solved: |
|||
echo "Solution:\n\n", $self |
|||
else: |
|||
echo "Unsolvable!" |
|||
var rows = ["850002400", |
|||
"720000009", |
|||
"004000000", |
|||
"000107002", |
|||
"305000900", |
|||
"040000000", |
|||
"000080070", |
|||
"017000000", |
|||
"000036040"] |
|||
var puzzle = Sudoku() |
|||
puzzle.init(rows) |
|||
puzzle.solve()</lang> |
|||
{{out}} |
|||
<pre>Starting grid: |
|||
8 5 0 | 0 0 2 | 4 0 0 |
|||
7 2 0 | 0 0 0 | 0 0 9 |
|||
0 0 4 | 0 0 0 | 0 0 0 |
|||
------+-------+------ |
|||
0 0 0 | 1 0 7 | 0 0 2 |
|||
3 0 5 | 0 0 0 | 9 0 0 |
|||
0 4 0 | 0 0 0 | 0 0 0 |
|||
------+-------+------ |
|||
0 0 0 | 0 8 0 | 0 7 0 |
|||
0 1 7 | 0 0 0 | 0 0 0 |
|||
0 0 0 | 0 3 6 | 0 4 0 |
|||
Solution: |
|||
8 5 9 | 6 1 2 | 4 3 7 |
|||
7 2 3 | 8 5 4 | 1 6 9 |
|||
1 6 4 | 3 7 9 | 5 2 8 |
|||
------+-------+------ |
|||
9 8 6 | 1 4 7 | 3 5 2 |
|||
3 7 5 | 2 6 8 | 9 1 4 |
|||
2 4 1 | 5 9 3 | 7 8 6 |
|||
------+-------+------ |
|||
4 3 2 | 9 8 1 | 6 7 5 |
|||
6 1 7 | 4 2 5 | 8 9 3 |
|||
5 9 8 | 7 3 6 | 2 4 1</pre> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |