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: same as input but with {ok} where .ok indicates success or failure.
# output: updated input on success, otherwise null.
def place($q; $n):
def place($queens; $n):
def place($q):
if $q == 0 then .ok = true
else .placingBlack = true
if $q == 0 then .ok = true
else .placingBlack = true
| label $out
| first(
| foreach range(0; $n) as $i (.;
foreach range (0; $n) as $j (.;
foreach range(0; $n) as $i (.;
{x:$i, y:$j} as $pos
foreach range(0; $n) as $j (.;
| .placingBlack as $placingBlack
{x:$i, y:$j} as $pos
| if any( .blackQueens[], .whiteQueens[];
| .placingBlack as $placingBlack
((.x == $pos.x) and (.y == $pos.y)))
| if any( .blackQueens[], .whiteQueens[];
then . # failure
((.x == $pos.x) and (.y == $pos.y)))
elif .placingBlack
then . # failure
then if any( .whiteQueens[]; isAttacking($pos) )
elif .placingBlack
then .
then if any( .whiteQueens[]; isAttacking($pos) )
else .blackQueens += [$pos]
then .
| .placingBlack = false
else .blackQueens += [$pos]
end
| .placingBlack = false
elif any( .blackQueens[]; isAttacking($pos) )
end
then .
elif any( .blackQueens[]; isAttacking($pos) )
else .whiteQueens += [$pos]
then .
| place($q-1; $n) as $place
else .whiteQueens += [$pos]
| if $place.ok then $place, break $out
| place($q-1) as $place
else .blackQueens |= .[:-1]
| if $place then $place # success
| .whiteQueens |= .[:-1]
else .blackQueens |= .[:-1]
| .placingBlack = true
| .whiteQueens |= .[:-1]
| .placingBlack = true
end
end
end
end
| if $i == $n-1 and $j == $n-1 then .ok = false end );
| if $i == $n-1 and $j == $n-1 then .ok = false end ) )
select(.ok) )
| select(.ok != null)
) // null
end;
end;
{blackQueens: [], whiteQueens: [] } | place($queens);


# 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)
(({blackQueens: [], whiteQueens: [] }
| place($t.queens; $t.squares)
| select(.)
| select(.ok)
| printBoard($t.squares))
| printBoard($t.squares))
// "No solution exists."),
// "No solution exists."),