How to resolve the algorithm 24 game/Solve step by step in the J programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm 24 game/Solve step by step in the J programming language
Table of Contents
Problem Statement
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm 24 game/Solve step by step in the J programming language
Source code in the j programming language
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
ops=: > , { 3#<'+-*%'
perms=: [: ":"0 [: ~. i.@!@# A. ]
build=: 1 : '(#~ 24 = ".) @: u'
combp=: dyad define
'a b c d'=. y['f g h'=. x
('(',a,f,b,g,c,')',h,d),('(',a,f,b,')',g,c,h,d),(a,f,'(',b,g,c,')',h,d),:('((',a,f,b,')',g,c,')',h,d)
)
math24=: monad define
assert. 4 = # y NB. prefer expressions without parens & fallback if needed
es=. ([: ,/ ops ([: , (' ',[) ,. ])"1 2/ perms) build y
if. 0 = #es do. es =. ([: ,/ [: ,/ ops combp"1 2/ perms) build y end.
es -."1 ' '
)
You may also check:How to resolve the algorithm Loops/Downward for step by step in the M4 programming language
You may also check:How to resolve the algorithm Playing cards step by step in the ZX Spectrum Basic programming language
You may also check:How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Haxe programming language
You may also check:How to resolve the algorithm Fractran step by step in the Ada programming language
You may also check:How to resolve the algorithm Main step of GOST 28147-89 step by step in the Wren programming language