Skip to main content

Ralsina.Me — Roberto Alsina's website

Brute Force Works

Last night, Juan­jo Con­ti tweet­ed this:

Or, in en­glish: "Us­ing ex­act­ly once the dig­its 1,3,4 and 6, and any of the four ba­sic op­er­a­tions, ob­tain 24."

I first spent a cou­ple of min­utes think­ing about it and then it hit me: there is no point in think­ing this sort of prob­lem, be­cause:

  1. Brute for­c­ing it will take less time

  2. What you do while "think­ing" it is sort of lame, is­n't it?

So, here is a more-or-­less gen­er­al so­lu­tion for any of these prob­lem­s.

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 =  ['*','/','+','-','']

t1='(({0}{4}{1}){5}{2}){6}{3}'
t2='{0}{4}({1}{5}({2}{6}{3}))'

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))
                #print(repr(s))
                try:
                    if eval(s) == target:
                        print(s)
                except (ZeroDivisionError, SyntaxError, TypeError):
                    continue

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) == -tar­get where you just need to add a unary - to the expression, but who cares.

Did I miss some­thing? Is this re­al­ly a gen­er­al so­lu­tion?


Contents © 2000-2024 Roberto Alsina