# Enigmatic Code

Programming Enigma Puzzles

## Enigma 1492: Magic magic

From New Scientist #2654, 3rd May 2008

I asked Albert and Berkeley to find 3 × 3 magic squares (i.e. containing nine different positive integers with the sum in each row, each column and main diagonal the same). They each found one. I then asked them to replace numbers with letters using A=1, B=2, and so on. Both their magic squares contained the letters M, A, G, I, C, but only in Albert’s case was one of those letters at the centre of the square.

(a) Which other four letters were used in Albert’s square?

(b) Which other four letters were used in Berkeley’s square?

[enigma1492]

### One response to “Enigma 1492: Magic magic”

1. Jim Randell 13 November 2012 at 10:01 am

The properties of a 3×3 Magic Square were explored in Enigma 1680.

The following Python program runs in 50ms.

```from itertools import permutations
from enigma import irange, printf

# permissible numbers
ns = set(irange(1, 26))

# MAGIC numbers (indexed from 1)
letters = '*ABCDEFGHIJKLMNOPQRSTUVWXYZ'
MAGIC = set(letters.index(c) for c in 'MAGIC')

# consider magic squares of the form:
#   s1 s2 s3
#   s4 s5 s6
#   s7 s8 s9
# with magic constant s
# for uniqueness we'll assume s1 is the smallest corner and s2 < s4

# consider the top row of the magic square
for (s1, s2, s3) in permutations(ns, 3):
if not(s1 < s3): continue
# determine the magic constant
s = s1 + s2 + s3
# and the other squares follow (see Enigma 1680)
(s5, r) = divmod(s, 3)
if r > 0: continue
s7 = s - (s3 + s5)
s8 = s - (s2 + s5)
s9 = s - (s1 + s5)
s4 = s - (s1 + s7)
s6 = s - (s3 + s9)
if not(s1 < s7 and s1 < s9 and s2 < s4): continue
# check the numbers in the square
ss = set((s1, s2, s3, s4, s5, s6, s7, s8, s9))
# they must all be different
if len(ss) != 9: continue
# and be allowable numbers
if not ss.issubset(ns): continue
# and contain MAGIC
if not MAGIC.issubset(ss): continue

# A's square has MAGIC in the middle, B's doesn't
label = ('A' if s5 in MAGIC else 'B')

# turn non-magic numbers into letters
xs = ''.join(sorted(letters[x] for x in (s1, s2, s3, s4, s5, s6, s7, s8, s9) if not x in MAGIC))

printf("{label}: [{s1} {s2} {s3} / {s4} {s5} {s6} / {s7} {s8} {s9}] {xs}")
```

Solution: (a) E K O Q, (b) B H N O.