2

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.

user47442
  • 21
  • 1
  • 1
    possible duplicate: http://mathematica.stackexchange.com/questions/15021/insert-times-into-123456789-to-make-it-equal-to-1 – vapor Mar 18 '17 at 07:17
  • 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? – Mr.Wizard Mar 23 '17 at 04:54

1 Answers1

6

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?

bobbym
  • 2,628
  • 2
  • 15
  • 20