Cryptarithm

Posted by CPUFreak91 on November 10th, 2008 filed in Programming, Project Difficulty: Hard, Python, Time Spent: More than 2 hours

Here’s my first attempt at brute-forcing a cryptarithm puzzle with no previous knowledge on how to solve them in Python.

The puzzle is: HACKER + HACKER + HACKER = ENERGY

The solutions are:
124536 + 124536 + 124536 = 373608
205463 + 205463 + 205463 = 616389

And here’s the code :).

# "Hacker"
# "Hacker"
# "Hacker"
#+________
# "Energy"

min = 100000 #Can't be less than 300,000 because 1/3 of it would be less than 100,000 which is less than the num of letters in hacker or energy

max = 333333
tries = 0
solutions = 0
listOfNumbers = []

for number in range(min, max):
listOfNumbers.append(number)

for number in listOfNumbers:
duplicate = False
sumString = list(str(number*3))
individualString = list(str(number))

for letter in individualString:
if individualString.count(letter) > 1:
duplicate = True

duplicate2 = False
duplicate3 = False
duplicate4 = False

sumString2 = [sumString[1], sumString[3], sumString[4], sumString[5]]
individualString2 = [individualString[0], individualString[1], individualString[2], individualString[3] ]
for letter in sumString2:
if sumString2.count(letter) > 1:
duplicate2 = True
for letter in sumString:
if sumString.count(letter) > 2:
duplicate4 = True

if duplicate == False:
if duplicate2 == False:
if duplicate4 == False:
if (sumString[0] == individualString[4]):
if (sumString[2] == individualString[4]):
if (sumString[3] == individualString[5]):
for digit in individualString2:
if digit == sumString2[0]:
duplicate3 = True
elif digit == sumString2[1]:
duplicate3 = True
elif digit == sumString2[2]:
duplicate3 = True
elif digit == sumString2[3]:
duplicate3 = True

if duplicate3 == False:
print number, “+”, number, “+”, number, “=”, number*3
solutions += 1

tries += 1

print “Took”, tries, “tries to generate”, solutions, “solutions.”

I first started out by generating and brute-forcing an array of numbers between 100,000 and 333,333. I looked for duplicate digits inside the numbers and sorted through them several times but making sure that the 5th digit of the summed numbers was the same as the 1st and 3rd of the sum of the numbers and that the 6th digit of the summed numbers was the same as the 4th digit of the sum of the numbers.

Leave a Comment

You must be logged in to post a comment.