N-queens problem: Difference between revisions

Content added Content deleted
(→‎{{header|Tailspin}}: Update to latest version. Use types more effectively)
Line 15,737: Line 15,737:
A solution using state to find one solution if any exist
A solution using state to find one solution if any exist
<lang tailspin>
<lang tailspin>
data r <"y">, c <"x">

templates queens
templates queens
def n: $;
def n: $;
templates getRowColumn
templates getRowColumn
when <?($@queens.freeRows($.r) <=0>)> do 0 !
when <?($@queens.freeRows($.r) <=0>)> do 0 !
when <?($@queens.freeMaxs(($.r + $.c)"1") <=0>)> do 0 !
when <?($@queens.freeMaxs($.r::raw + $.c::raw) <=0>)> do 0 !
when <?($@queens.freeMins(($.c - $.r + $n)"1") <=0>)> do 0 !
when <?($@queens.freeMins($.c::raw - $.r::raw + $n) <=0>)> do 0 !
otherwise 1!
otherwise 1!
end getRowColumn
end getRowColumn
Line 15,750: Line 15,748:
sink setRowColumn
sink setRowColumn
def p: $;
def p: $;
@queens.freeRows($p.r): $p.val;
@queens.freeRows($p.r): $p.val::raw;
@queens.freeMaxs(($p.c + $p.r)"1"): $p.val;
@queens.freeMaxs($p.c::raw + $p.r::raw): $p.val::raw;
@queens.freeMins(($p.c - $p.r + $n)"1"): $p.val;
@queens.freeMins($p.c::raw - $p.r::raw + $n): $p.val::raw;
end setRowColumn
end setRowColumn

data done <=1>


templates placeQueen
templates placeQueen
def c: ($)"x";
def c: $;
1"y" -> #
row´1 -> #
when <='done'> do 1!
when <done> do 1!
when <=($n+1)"y"> do 0 !
when <=row´($n+1)> do 0 !
when <?({r: $, c: $c} -> getRowColumn <=1>)> do
when <?({r: $, c: $c} -> getRowColumn <=1>)> do
def r: $;
def r: $;
@queens.queenRows($r): $c;
@queens.queenRows($r): $c;
{r: $, c: $c, val: 0} -> !setRowColumn
{r: $, c: $c, val: 0} -> !setRowColumn
$c -> \(
$c -> \(<=col´$n> done´1!
when <=($n)"x"> do 'done'!
<?(col´($c::raw + 1) -> placeQueen <=1>)> done´1!
<>
when <?($c + 1 -> placeQueen <=1>)> do 'done'!
otherwise
{r: $r, c: $c, val: 1} -> !setRowColumn
{r: $r, c: $c, val: 1} -> !setRowColumn
$r + 1 !
row´($r::raw + 1) !\) -> #
\) -> #
otherwise row´($::raw + 1) -> #
otherwise $ + 1 -> #
end placeQueen
end placeQueen


Line 15,778: Line 15,776:
freeMins: [1..$n*2 -> 1],
freeMins: [1..$n*2 -> 1],
queenRows: [1..$n -> -1] };
queenRows: [1..$n -> -1] };
1 -> placeQueen -> \(<=1> $@queens.queenRows ! <> 'non-existent'!\)!
col´1 -> placeQueen -> \(<=1> $@queens.queenRows ! <> 'non-existent'!\)!
end queens
end queens