task

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.



Related task

   Arithmetic Evaluator


var [const] H=Utils.Helpers;
fcn u(xs){ xs.reduce(fcn(us,s){us.holds(s) and us or us.append(s) },L()) }
var ops=u(H.combosK(3,"+-*/".split("")).apply(H.permute).flatten());
var fs=T(
   fcn f0(a,b,c,d,x,y,z){ Op(z)(Op(y)(Op(x)(a,b),c),d) }, // ((AxB)yC)zD
   fcn f1(a,b,c,d,x,y,z){ Op(y)(Op(x)(a,b),Op(z)(c,d)) }, // (AxB)y(CzD)
   fcn f2(a,b,c,d,x,y,z){ Op(z)(Op(x)(a,Op(y)(b,c)),d) }, // (Ax(ByC))zD
   fcn f3(a,b,c,d,x,y,z){ Op(x)(a,Op(z)(Op(y)(b,c),d)) }, // Ax((ByC)zD)
   fcn f4(a,b,c,d,x,y,z){ Op(x)(a,Op(y)(b,Op(z)(c,d))) }, // Ax(By(CzD))
);
 
var fts= // format strings for human readable formulas
  T("((d.d).d).d", "(d.d).(d.d)", "(d.(d.d)).d", "d.((d.d).d)", "d.(d.(d.d))")
  .pump(List,T("replace","d","%d"),T("replace",".","%s"));
 
fcn f2s(digits,ops,f){
   fts[f.name[1].toInt()].fmt(digits.zip(ops).flatten().xplode(),digits[3]);
}
 
fcn game24Solver(digitsString){
   digits:=digitsString.split("").apply("toFloat");
   [[(digits4,ops3,f); H.permute(digits); ops;    // list comprehension
     fs,{ try{f(digits4.xplode(),ops3.xplode()).closeTo(24,0.001) }
          catch(MathError){ False } };
     { f2s(digits4,ops3,f) }]];
}