Jump to content

Solve the no connection puzzle: Difference between revisions

→‎{{header|jq}}: revise for jq 1.6
No edit summary
(→‎{{header|jq}}: revise for jq 1.6)
Line 2,564:
 
=={{header|jq}}==
{{works with|jq|1.46}}
'''Also works with gojq, the Go implementation of jq'''
 
We present a generate-and-test solver for a slightly more general version of the problem, in which there are N pegs and holes, and in which the connectedness of holes is defined by an array such that holes i and j are connected if and only if [i,j] is a member of the
array.
Line 2,574 ⟶ 2,576:
 
'''Part 1: Generic functions'''
<syntaxhighlight lang="jq"># Short-circuit determination of whether (a|condition)
# permutations of 0 .. (n-1) inclusive
# is true for all a in array:
def forall(array; condition):
def check:
. as $ix
| if $ix == (array|length) then true
elif (array[$ix] | condition) then ($ix + 1) | check
else false
end;
0 | check;
 
# permutations of 0 .. (n-1)
def permutations(n):
# Given a single array, generate a stream by inserting n at different positions:
Line 2,597 ⟶ 2,589:
 
# Count the number of items in a stream
def count(f): reduce f as $_ (0; .+1);</syntaxhighlight>
</syntaxhighlight>
 
'''Part 2: The no-connections puzzle for N pegs and holes'''
<syntaxhighlight lang="jq"># Generate a stream of solutions.
# Generate a stream of solutions.
# Input should be the connections array, i.e. an array of [i,j] pairs;
# N is the number of pegs and holds.
Line 2,609 ⟶ 2,602:
def ok(connections):
. as $p
| forallall( connections[];
(($p[.[0]] - $p[.[1]])|abs) != 1 );
 
. as $connections | permutations(N) | select(ok($connections));</syntaxhighlight>
</syntaxhighlight>
'''Part 3: The 8-peg no-connection puzzle'''
<syntaxhighlight lang="jq"># The connectedness matrix:
# The connectedness matrix
# In this table, 0 represents "A", etc, and an entry [i,j]
# signifies that the holes with indices i and j are connected.
Line 2,653 ⟶ 2,648:
# To count the number of solutions:
# count(solve)
# => 16
 
onelimit(1; solve) | pp
# jq 1.4 lacks facilities for harnessing generators,
# but the following will suffice here:
def one(f): reduce f as $s
(null; if . == null then $s else . end);
 
one(solve) | pp
</syntaxhighlight>
{{outoutput}}
<syntaxhighlight lang="sh">$Invocation: jq -n -r -f no_connection.jq
<pre>
 
5 6
/|\ /|\
Line 2,672 ⟶ 2,663:
\ | X | /
\|/ \|/
3 4</syntaxhighlight>
</pre>
 
=={{header|Julia}}==
2,484

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.