Jump to content

Sudoku: Difference between revisions

m
→‎{{header|Tailspin}}: handle autotyping of tagged identifiers
m (→‎{{header|Tailspin}}: handle autotyping of tagged identifiers)
Line 12,305:
<lang tailspin>
templates deduceRemainingDigits
data row <"1">, col <"1"> local
templates findOpenPosition
@:{options: 10};
Line 12,310 ⟶ 12,311:
$@ !
end findOpenPosition
 
templates selectFirst&{pos:}
def digit: $($pos.row;$pos.col) -> $(1);
Line 12,321 ⟶ 12,322:
\) !
end selectFirst
 
@: $;
$ -> findOpenPosition -> #
Line 12,330 ⟶ 12,331:
-> \(when <~=[]> do @deduceRemainingDigits: $; {options: 10} !
when <=[]> do ^@deduceRemainingDigits($next.row;$next.col;1)
-> { $next..., options: $next.options::raw-1} ! \) -> #
end deduceRemainingDigits
 
test 'internal solver'
def sample: [
Line 12,345 ⟶ 12,346:
[3,4,5,2,8,6,1,7,9]
];
 
assert $sample -> deduceRemainingDigits <=$sample> 'completed puzzle unchanged'
 
assert [
[[5],3,4,6,7,8,9,1,2],
$sample(2..last)...] -> deduceRemainingDigits <=$sample> 'final digit gets placed'
 
assert [
[[],3,4,6,7,8,9,1,2],
$sample(2..last)...] -> deduceRemainingDigits <=[]> 'no remaining options returns empty'
 
assert [
[[5],3,4,6,[2,5,7],8,9,1,[2,5]],
$sample(2..last)...] -> deduceRemainingDigits <=$sample> 'solves 3 digits on row'
 
assert [
[5,3,4,6,7,8,9,1,2],
Line 12,371 ⟶ 12,372:
[3,4,5,2,8,6,1,7,9]
] -> deduceRemainingDigits <=$sample> 'solves 3 digits on column'
 
assert [
[5,3,[4,6],6,7,8,9,1,2],
Line 12,378 ⟶ 12,379:
$sample(4..last)...
] -> deduceRemainingDigits <=$sample> 'solves 3 digits in block'
 
// This gives a contradiction if 3 gets chosen out of [3,5]
assert [
Line 12,384 ⟶ 12,385:
$sample(2..last)...] -> deduceRemainingDigits <=$sample> 'contradiction is backtracked'
end 'internal solver'
 
composer parseSudoku
[<section>=3]
Line 12,393 ⟶ 12,394:
rule dot: <'\.'> -> [1..9 -> '$;']
end parseSudoku
 
test 'input sudoku'
def parsed:
Line 12,407 ⟶ 12,408:
...|419|..5
...|.8.|.79' -> parseSudoku;
 
assert $parsed <[<[<[]>=9](9)>=9](9)> 'parsed sudoku has 9 rows containing 9 columns of lists'
assert $parsed(1;1) <=['5']> 'a digit'
assert $parsed(1;3) <=['1','2','3','4','5','6','7','8','9']> 'a dot'
end 'input sudoku'
 
templates solveSudoku
$ -> parseSudoku -> deduceRemainingDigits -> #
Line 12,421 ⟶ 12,422:
\) -> '$...;' !
end solveSudoku
 
test 'sudoku solver'
assert
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.