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


  [ ' [ 0 1 2 3 ]
    permutations ] constant          is numorders (         --> [ )
 
  [ []
    4 3 ** times
      [ [] i^
        3 times
          [ 4 /mod 4 +
            rot join swap ]
        drop 
        nested join ] ] constant     is oporders  (         --> [ )
 
  [ [] numorders witheach
      [ oporders witheach
        [ dip dup join nested
          rot swap join swap ]
        drop ] ] constant            is allorders (         --> [ )
 
  [ [] unrot witheach
      [ dip dup peek
        swap dip [ nested join ] ]
    drop ]                           is reorder   (     [ [ --> [ )
 
  [ ' [ [ 0 1 4 2 5 3 6 ]
        [ 0 1 4 2 3 5 6 ]
        [ 0 1 2 4 3 5 6 ] ]
    witheach
      [ dip dup reorder swap ]
    4 pack ]                         is orderings (       [ --> [ )
 
  [ witheach
      [ dup number? iff n->v done
        dup ' + = iff
          [ drop v+ ] done
        dup ' - = iff
          [ drop v- ] done
            ' * = iff v* done
        v/ ]
    24 n->v v- v0= ]                 is 24=       (       [ --> b )
 
  [ 4 pack sort
    [] swap
    ' [ + - * / ] join
    allorders witheach
      [ dip dup reorder orderings
        witheach 
          [ dup 24= iff
              [ rot swap
                nested join swap ]
            else drop ] ]
    drop
    uniquewith
      [ dip unbuild unbuild $> ]
    dup size
    dup 0 = iff
       [ 2drop say "No solutions." ]
       done
    dup 1 = iff
      [ drop say "1 solution." ]
    else
      [ echo say " solutions." ]
    unbuild
    2 split nip
    -2 split drop nest$ 90 wrap$ ]   is solve     ( n n n n -->   )