# Enigmatic Code

Programming Enigma Puzzles

## Enigma 431: Error in the code

From New Scientist #1581, 8th October 1987 [link]

In the addition sum below, letters have been substituted for digits. It was Uncle Bungle’s intention, when he made this sum up, that the same letter should stand for the same digit wherever it appeared, and that different letters should stand for different digits. Unfortunately, however, he made a mistake, and one of the letters is incorrect.

Write out the correct sum with digits substituted for letters.

[enigma431]

### One response to “Enigma 431: Error in the code”

1. Jim Randell 12 January 2018 at 9:55 am

We’ve solved many puzzles in a similar vein to this one before. (See: Enigma 405, Enigma 284, Enigma 197, Enigma 29, Puzzle 76).

Here I’ve adapted my MiniZinc solution to Enigma 197 to solve this problem. This program uses the minizinc.py wrapper library. With the [[ mzn-g12fd -a ]] solver it runs in 442 ms.

```from enigma import substitute
from minizinc import MiniZinc, var, alphametic

p = MiniZinc(f"""

include "globals.mzn";

% the symbols in the incorrect sum
{var("0..9", "ABHLPRXY")};

constraint all_different([A, B, H, L, P, R, X, Y]);

% make a new sum: abcdef + ghijkmn = pqrstuvw
{var("0..9", "abcdefghijkmnpqrstuvw")};

constraint a != 0 /\ g != 0 /\ p != 0;

% the new sum is a correct alphametic sum
constraint {alphametic("{abcdef} + {ghijkmn} = {pqrstuvw}")};

% and differs from the original incorrect sum in only one place
constraint sum([
a != P, b != H, c != H, d != Y, e != B, f != B,
g != P, h != L, i != H, j != X, k != H, m != A, n != B,
p != L, q != R, r != R, s != P, t != Y, u != B, v != H, w != P,
]) = 1;

solve satisfy;

""")

for s in p.solve(solver="mzn-g12fd -a", verbose=0):
print(substitute(s, "abcdef + ghijkmn = pqrstuvw"))
```

Solution: The correct numerical sum is: 944277 + 9148467 = 10092744.

The corresponding alphametic sum is: PHHYBB + PLHXHAB = LRRPYBHH.

The incorrect letter is the units digit of the result. It is given as P, when it should be H.

Another approach is to use the SubstitutedSum() solver from the enigma.py library.

Here is a general solver for this type of problem. This program runs in 773 ms.

Run: [ @repl.it ]

```from enigma import SubstitutedSum, printf

# solve the bungled alphametic sum <X> + <Y> = <Z>
# where one of the symbols given is incorrect
def bungled_sum(X, Y, Z):

text = X + Y + Z
letters = set(text + '?')
j = len(X)
k = j + len(Y)

# choose a letter to replace
for (i, x) in enumerate(text):
# choose the replacement letter
for y in letters:
if x == y: continue
# replace the letter
t = text[:i] + y + text[i + 1:]
# create the sum
p = SubstitutedSum([t[:j], t[j:k]], t[k:])
# solve it