Magic squares


Derive a 3×3 grid with random arrangements of number from 1 to 9 inclusive, where the sum of the diagonal, vertical and horizontal numbers are equal.
A | B | C
D | E | F
G | H | I
A+B+C = D+E+F = G+H+I = A+E+I = C+E+G

Most people may not know but this is actually an IQ test problem and falls under what we call an optimization problem. Optimization problems can be solved by brute force or more efficiently using genetic algorithms. Since the search space is quite small (84 combinations) I solved this quickly using a brute force method

First set the stage by importing random, setting variables and sample space

import random
k = [x for x in xrange(1,10)]
k1,k2,k3 = [1],[2],[3]

Then keep looking until the diagonals, horizontals and verticals are the same sum

while sum(k1)!=sum(k2)\
or sum(k2)!=sum(k3)\
or sum([k1[0],k2[1],k3[2]]) == sum(k1)\
or sum([k1[2],k2[1],k3[0]]) == sum(k2):
    k1 = random.sample(k,3)
    k2 = [x for x in random.sample(k,9) if x not in k1][:3]
    k3 = [x for x in random.sample(k,9) if x not in k1 and x not in k2][:3]

print k1, sum(k1)
print k2, sum(k2)
print k3, sum(k3)
print sum(k1),sum(k2),sum(k3)

This same problem can be solved in R using the magic package


And manually by arranging the numbers in order 1 2 3 4 5 6 7 8 9. We see that 5 is a centriod with equal amount of numbers on either end, but their sums are imbalanced (sum(1,2,3,4) <> sum(6,7,8,9)). So first re-arrange the numbers so that their sums are equal 8 2 3 7 5 4 6 1 9 (sum(8,2,3,7) = sum(4,6,1,9)). Then take contiguous numbers from either side starting from outer and sum it with 5, eg. 951 = 852 = 357 = 456, notice 5 is always in the center. Five now becomes your center box and the other numbers make a cross around 5.
? 7 ?
9 5 1
? 3 ?
Now you just need to fit in the 456 and 852. I will leave you to comment, with your answer. Gotta love math!