Peaceful chess queen armies: Difference between revisions
Content added Content deleted
(→{{header|jq}}: simplify) |
|||
Line 4,913: | Line 4,913: | ||
'''Works with gojq, the Go implementation of jq''' |
'''Works with gojq, the Go implementation of jq''' |
||
In the following, positions on the chessboard are represented by {x,y} objects. |
In the following, positions on the chessboard are represented by {x,y} objects. |
||
<syntaxhighlight lang="jq"> |
<syntaxhighlight lang="jq"> |
||
Line 4,926: | Line 4,925: | ||
# and similarly for .whiteQueens. |
# and similarly for .whiteQueens. |
||
# input: {blackQueens, whiteQueens} |
# input: {blackQueens, whiteQueens} |
||
# output: |
# output: updated input on success, otherwise null. |
||
def place($ |
def place($queens; $n): |
||
def place($q): |
|||
if $q == 0 then .ok = true |
|||
if $q == 0 then .ok = true |
|||
else .placingBlack = true |
|||
| label $out |
|||
| first( |
|||
| foreach range(0; $n) as $i (.; |
|||
foreach range |
foreach range(0; $n) as $i (.; |
||
foreach range(0; $n) as $j (.; |
|||
{x:$i, y:$j} as $pos |
|||
| .placingBlack as $placingBlack |
|||
| if any( .blackQueens[], .whiteQueens[]; |
|||
((.x == $pos.x) and (.y == $pos.y))) |
|||
then . # failure |
|||
elif .placingBlack |
|||
then if any( .whiteQueens[]; isAttacking($pos) ) |
|||
then . |
|||
else .blackQueens += [$pos] |
|||
| .placingBlack = false |
|||
end |
|||
elif any( .blackQueens[]; isAttacking($pos) ) |
|||
then . |
|||
else .whiteQueens += [$pos] |
|||
| |
| place($q-1) as $place |
||
| if $place then $place # success |
|||
else .blackQueens |= .[:-1] |
|||
| . |
| .whiteQueens |= .[:-1] |
||
| .placingBlack = true |
|||
end |
|||
end |
end |
||
end |
| if $i == $n-1 and $j == $n-1 then .ok = false end ); |
||
select(.ok) ) |
|||
) // null |
|||
end; |
end; |
||
⚫ | |||
# Input {blackQueens, whiteQueens} |
# Input {blackQueens, whiteQueens} |
||
Line 4,989: | Line 4,991: | ||
tasks[] as $t |
tasks[] as $t |
||
| "\($t.queens) black and \($t.queens) white queens on a \($t.squares) x \($t.squares) board:", |
| "\($t.queens) black and \($t.queens) white queens on a \($t.squares) x \($t.squares) board:", |
||
((place($t.queens; $t.squares) |
|||
⚫ | |||
| |
| select(.) |
||
| select(.ok) |
|||
| printBoard($t.squares)) |
| printBoard($t.squares)) |
||
// "No solution exists."), |
// "No solution exists."), |