2
$\begingroup$

I would like to use Mathematica to create a simple program in which we can find all ways to construct 21 by using each of 1, 5, 6, and 7 exactly once. The numbers may be combined in any way using any of the primary binary operators, i.e. addition, subtraction, multiplication, and division, as well as parenthesis. I feel that the method of brute-forcing all possible combinations of 1, 5, 6 and 7 would likely be effective, but I am having trouble structuring the code. My approach would likely be the following:

  1. Define a vector S = (1, 5, 6, 7)
  2. Remove any two numbers in S and perform an arbitrary binary operation on the two numbers, obtaining a new number a.
  3. Replace a into S, generating S'.
  4. Repeat from step 1 until this particular brute-force branch generates a final value.

Hence, the cycle would repeat until S reduces to one element. If the branch results in 21, we would be done. The problem is I do not know how to code steps 2 and 3 in Mathematica, and would like some help on how to structure my code, or if my approach isn't efficient, on changing up my approach.

$\endgroup$
2
  • 1
    $\begingroup$ possible duplicate: mathematica.stackexchange.com/questions/15021/… $\endgroup$
    – vapor
    Commented Mar 18, 2017 at 7:17
  • $\begingroup$ user47442, I am inclined to close this question as a duplicate of the one happy fish proposed above. Do you agree? If not what is your case for differentiating it? $\endgroup$
    – Mr.Wizard
    Commented Mar 23, 2017 at 4:54

1 Answer 1

6
$\begingroup$

Maybe this can help...There is the new in 11 Groupings command but it only gets one answer?!

ans = Groupings[Permutations[{1, 5, 6, 7}], {Plus, Subtract, Times, Divide} -> 2, HoldForm]
Quiet[Select[ans, ReleaseHold[#] == 21 &]]

$$\frac{6}{1-\frac{5}{7}}$$

The first line is straight from the docs, can the second line be improved? Are there more solutions?

$\endgroup$
2
  • 3
    $\begingroup$ thanks for introducing me to Groupings`+1:) $\endgroup$
    – ubpdqn
    Commented Mar 18, 2017 at 8:58
  • $\begingroup$ @ubpdqn, you are very welcome. $\endgroup$
    – bobbym
    Commented Mar 18, 2017 at 17:41

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.