24 game/Solve: Difference between revisions

Content added Content deleted
m (→‎{{header|Ruby}}: use rational arithmetic)
(J)
Line 127: Line 127:
(((9 - 3) * 8) / 2)
(((9 - 3) * 8) / 2)
(8 / (2 / (9 - 3)))</pre>
(8 / (2 / (9 - 3)))</pre>

=={{header|J}}==
<lang J>perm=: (A.&i.~ !) 4
ops=: ' ',.'+-*%' {~ >,{i.each 4 4 4
cmask=: 1 + 0j1 * i.@{:@$@[ e. ]
left=: [ #!.'('~"1 cmask
right=: [ #!.')'~"1 cmask
paren=: 2 :'[: left&m right&n'
parens=: ], 0 paren 3, 0 paren 5, 2 paren 5, [: 0 paren 7 (0 paren 3)
all=: [: parens [:,/ ops ,@,."1/ perm { [:;":each
answer=: ({.@#~ 24 = ".)@all</lang>

This implementation tests all 7680 candidate sentences.

Example use:

answer 2 3 5 7
2+7+3*5

The answer will be either a suitable J sentence or blank if none can be found.


=={{header|Mathematica}}==
=={{header|Mathematica}}==