24 game/Solve: Difference between revisions

jq
No edit summary
(jq)
Line 3,096:
((6*8)/((9-7)))
(((1+7))*(2+1))</pre>
 
=={{header|jq}}==
{{works with|jq|1.4}}
'''Infrastructure:'''
<lang jq># Generate a stream of the permutations of the input array.
def permutations:
if length == 0 then []
else
. as $in | range(0;length) | . as $i
| ($in|del(.[$i])|permutations)
| [$in[$i]] + .
end ;
 
# Generate a stream of all the distinct arrays of length n,
# with members drawn from the input array.
def take(n):
length as $l |
if n == 1 then range(0;$l) as $i | [ .[$i] ]
else take(n-1) + take(1)
end;</lang>
'''Evaluation and pretty-printing of allowed expressions'''
<lang jq># Evaluate the input, which must be a number or a triple: [x, op, y]
def eval:
if type == "array" then
.[1] as $op
| if .[0] == null or .[2] == null then null
else
(.[0] | eval) as $left | (.[2] | eval) as $right
| if $left == null or $right == null then null
elif $op == "+" then $left + $right
elif $op == "-" then $left - $right
elif $op == "*" then $left * $right
elif $op == "/" then
if $right == 0 then null
else $left / $right
end
else "invalid arithmetic operator: \($op)" | error
end
end
else .
end;
 
def pp:
"\(.)" | explode | map([.] | implode | if . == "," then " " elif . == "\"" then "" else . end) | join("");</lang>
 
'''24 Game''':
<lang jq>def OBJECTIVE: 24;
 
def OPERATORS: ["+", "-", "*", "/"];
 
# Input: an array of 4 digits
# o: an array of 3 operators
# Output: a stream
def EXPRESSIONS(o):
[ [ [.[0], o[0], .[1]], o[1] , .[2]], o[2], .[3] ],
[ [ .[0], o[0], [.[1], o[1], .[2]]], o[2], .[3] ],
[ [ .[0], o[0], .[1]], o[1] ,[.[2], o[2], .[3] ]],
[ .[0], o[0],[[.[1], o[1] , .[2]], o[2], .[3] ]],
[ .[0], o[0], [.[1], o[1] ,[.[2], o[2], .[3]]]]
;
 
def solve:
[ (OPERATORS | take(3)) as $poperators
| permutations | EXPRESSIONS($poperators)
| select( eval == OBJECTIVE)
] as $answers
| if $answers|length > 3 then
"That was too easy. I found \($answers|length) answers, e.g. \($answers[0] | pp)"
elif $answers|length > 3 then $answers[] | pp
else "You lose! There are no solutions."
end
;
 
solve, "Please try again."</lang>
{{out}}
<lang sh>$ jq -r -f eval.jq
[1,2,3,4]
That was too easy. I found 242 answers, e.g. [[[1 + 2] + 3] * 4]
Please try again.
[10,20,3,4]
That was too easy. I found 85 answers, e.g. [[[20 / 10] * 3] * 4]
Please try again.
[10,10,3,4]
That was too easy. I found 32 answers, e.g. [[[10 * 3] - 10] + 4]
Please try again.
[23,1,1,1]
That was too easy. I found 1002 answers, e.g. [[[23 - 1] + 1] + 1]
Please try again.
[24,6,26,0]
That was too easy. I found 126 answers, e.g. [24 + [[6 + 26] * 0]]
Please try again.
[24,6,26,9]
That was too easy. I found 9 answers, e.g. [6 - [[24 - 26] * 9]]
Please try again.</lang>
 
=={{header|Julia}}==
2,458

edits