1
$\begingroup$

Consider 3* 2 + 2 /4*10

With the default precedence for *,+, and / the result is 11.

I am curious what the results would be for all six choices for the precedence of the +,*, and /

I'm also curious what the set of results would be for all parenthetic groupings. (e.g, 3* (2 + 2) /4*10,3* ((2 + 2) /4)*10,etc)

Can anyone see how to do that?

$\endgroup$

1 Answer 1

1
$\begingroup$
stripParentheses = Function[, StringReplace["(" | ")" | " " -> ""] @
    ToString[Unevaluated @ #, InputForm], HoldFirst];

stripParentheses[3*2 + 2/4*10]

enter image description here

ops = {"/", "*", "+"};

split = StringSplit[stripParentheses[3*2 + 2/4*10], a : Alternatives @@ ops :> a]

enter image description here

parenthesize = SequenceReplace[#, {a_, #2, b_} :> StringJoin["(",a,#2,b,")"]]&;


Map[{#, ## & @@ {StringJoin @ #, ToExpression @ StringJoin @ #} & @
   Fold[parenthesize, split, #]} &] @ Permutations[ops] // 
 Grid[#, Dividers -> All] &

enter image description here

$\endgroup$
1
  • $\begingroup$ Excellent. I am still spelunking your code. This answers the first part. Thanks. I'm trying to adapt it to also do the second part (e.g.,` (3*2 + 2/4)*10` = 65 $\endgroup$ Commented Jul 3, 2023 at 8:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.