暴力求解24点

思路很简单

递归生成列表树 暴力求解

Test

game24play[{4, 5, 6, 7}]
{"4*(5 - 6 + 7)", "(-4 + 6)*(5 + 7)"}

game24play[{3, 4, 5, 1}]
{"3 + 4*5 + 1", "3*(4 + 5 - 1)", "(3 + 5)*(4 - 1)", "4 + 5*(3 + 1)"}

代码如下

treeR[n_] := Table[o[treeR[a], treeR[n - a]], {a, 1, n - 1}]
treeR[1] := n
tree[n_] := 
 Flatten[treeR[n] //. {o[a_List, b_] :> (o[#, b] & /@ a), 
    o[a_, b_List] :> (o[a, #] & /@ b)}]
game24play[val_List] := 
 Union[StringReplace[StringTake[ToString[#, InputForm], {10, -2}], 
     "-1*" ~~ n_ :> "-" <> n] & /@ (HoldForm /@ 
      Select[Union@
        Flatten[Outer[# /. {o[q_Integer] :> #2[[q]], 
             n[q_] :> #3[[q]]} &, 
          Block[{O = 1, N = 1}, # /. {o :> o[O++], n :> n[N++]}] & /@ 
           tree[4], Tuples[{Plus, Subtract, Times, Divide}, 3], 
          Permutations[Array[v, 4]], 1]], 
       Quiet[(# /. v[q_] :> val[[q]]) == 24] &] /. 
     Table[v[q] -> val[[q]], {q, 4}])]

The treeR method recursively computes all possible operator trees for a certain number of inputs. It does this by tabling all combinations of distributions of inputs across the possible values. (For example, treeR[4] is allotted 4 inputs, so it returns {o[treeR[3],treeR[1]],o[treeR[2],treeR[2]],o[treeR[1],treeR[3]]}, where o is the operator (generic at this point). The base case treeR[1] returns n (the input). The final output of tree[4] (the 24 game has 4 random inputs)

结果基本秒出