2015-10-28 15:24

Brute Force Works

Last night, Juanjo Conti tweeted this:

Or, in english: "Using exactly once the digits 1,3,4 and 6, and any of the four basic operations, obtain 24."

I first spent a couple of minutes thinking about it and then it hit me: there is no point in thinking this sort of problem, because:

  1. Brute forcing it will take less time
  2. What you do while "thinking" it is sort of lame, isn't it?

So, here is a more-or-less general solution for any of these problems.

from __future__ import print_function, division
import itertools

numbers = ['1','3','4','6']
target = 24

# Having '' as an operation allows for solution (14-6)*3, which
# may or may not be valid depending on rule interpretation.
operations =  ['*','/','+','-','']


for nums in itertools.permutations(numbers):
    for ops1 in itertools.combinations_with_replacement(operations, 3):
        for ops2 in itertools.permutations(ops1):
            for t in (t1, t2):
                s = t.format(*(nums+ops2))
                    if eval(s) == target:
                except (ZeroDivisionError, SyntaxError, TypeError):

Of course you can make it solve any problem of this class by adjusting numbers and target. There is also a possible extra solution if eval(s) == -target where you just need to add a unary - to the expression, but who cares.

Did I miss something? Is this really a general solution?


Comments powered by Disqus

Contents © 2000-2019 Roberto Alsina