I am trying to solve the following problem:
A store sells large individual wooden letters for signs to put on houses.
The letters are priced individually.
The total cost of letters in LOAN is 17 dollars.
The total cost of letters in SAM is 18 dollars.
The total cost of letters in ANNA is 20 dollars.
The total cost of letters in ROLLO is 21 dollars.
The total cost of letters in DAMAGES is 30 dollars.
The total cost of letters in SALMON is 33 dollars.
How much would the letters in the name GARDNER cost?
I am brute-forcing letters cost with the following python code, but it take hours and hours to converge, as their are 33^10 possible combinaisons to test. I use n=33 as it is the max cost of a name but indeed, n can be reduced to 15 or even 10, but without being sur it will converge.
def func(letters):
print letters
if letters['L']+letters['O']+letters['A']+letters['N'] != 17:
return False
elif letters['S']+letters['A']+letters['M'] != 18:
return False
elif 2*letters['A']+2*letters['N'] != 20:
return False
elif letters['R']+2*letters['O']+2*letters['L'] != 21:
return False
elif letters['D']+2*letters['A']+letters['M']+letters['G']+letters['E']+letters['S'] != 30:
return False
elif letters['S']+letters['A']+letters['L']+letters['M']+letters['O']+letters['N'] != 33:
return False
return True
def run(letters, n, forbidden_letters):
for letter in letters.keys():
if letter not in forbidden_letters:
for i in range(1, n):
letters[letter] = i
if not func(letters):
if letter not in forbidden_letters:
forbidden_letters+=letter
if run(letters, n, forbidden_letters):
return letters
else:
return letters
LETTERS = {
"L":1,
"O":1,
"A":1,
"N":1,
"S":1,
"M":1,
"R":1,
"D":1,
"G":1,
"E":1,
}
n=33
print run(LETTERS, n, "")
Brute-forcing will work in the end, but it is so CPU extensive that it is surely not the best solution.
Does anyone have a better solution to solve this problem? Either by reducing the computation time, either by a good math approach.
Thanks all.
This is what is called a system of linear equations. You can solve this by hand if you want, but you can also use a linear solver. For example with sympy
import sympy
l,o,a,n,s,m,r,d,g,e = sympy.symbols('l,o,a,n,s,m,r,d,g,e')
eq1 = l+o+a+n - 17
eq2 = s+a+m -18
eq3 = a+n+n+a -20
eq4 = r+o+l+l+o -21
eq5 = d+a+m+a+g+e+s -30
eq6 = s+a+l+m+o+n- 33
sol, = sympy.linsolve([eq1,eq2,eq3,eq4,eq5,eq6],(l,o,a,n,s,m,r,d,g,e))
l,o,a,n,s,m,r,d,g,e = sol
print(g+a+r+d+n+e+r)
Linear equations can be solved very fast. The complexity is O(n3), where n is the number of variables. So for such a little problem as this it is near instant.