ops = Map[Inactive,
Tuples[{Times, Plus, Subtract, Divide}, {4 - 1}], {2}];
rules = Thread[{a, b, c} -> #] & /@ ops;
matchQ[list_] :=
Module[{},
res = Fold[Replace[#1, List -> #2[[1]], {#2[[2]]}, Heads -> True] &,
list, Transpose@{{a, b, c}, {1, 2, 3}}] /. rules //.
Inactive[Subtract][x_, y_] :> Inactive[Plus][x, -y];
Select[res, Activate[#] == 24 &]]
list = {6, 4, 2, 3};
pattern = {{#[[1 ;; 2]], #[[3 ;; 4]]}, {#[[
1]], {#[[2]], #[[3 ;; 4]]}},
Reverse@{#[[1]], {#[[2]], #[[3 ;; 4]]}}, {{{#[[1]], #[[2]]}, #[[
3]]}, #[[4]]}, Reverse@{{{#[[1]], #[[2]]}, #[[3]]}, #[[4]]}} &;
parts = Flatten[(pattern) /@ Permutations[list, {4}], 1];
res1 = matchQ /@ parts // Quiet // Flatten;
When I'm playing with a calculating 24, I used some function like Inactive
. My question is how can I make the output more reasonble in human writing habbit? For example, here I replace Subtract
with Plus
.
I want to change ((6+4)+-2)*3
to ((6+4)-2)*3
StringForm
is also OK, just for display
res1[[1]]
(*
((6+4)+-2)*3
*)
Comments
Post a Comment