MATHEMATICS

Jumat, 22 Juli 2011

Magic squares - Revisited

Regular readers of this blog know that I am fascinated by magic squares. Finding the 3 by 3 magic square with digits 1,2, ..., 9 can be formulated as an Integer Programming problem. An Integer Programming problem is a Linear Programming problem with the additional constraints that all variables must have integer values.

c={1,1,1,1,1,1,1,1,1};
m={
{1,1,1,0,0,0,0,0,0},
{0,0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,1,1,1},
{1,0,0,1,0,0,1,0,0},
{0,1,0,0,1,0,0,1,0},
{0,0,1,0,0,1,0,0,1},
{1,0,0,0,1,0,0,0,1},
{0,0,1,0,1,0,1,0,0},
{-1,-1,-1,0,0,0,0,0,0},
{0,0,0,-1,-1,-1,0,0,0},
{0,0,0,0,0,0,-1,-1,-1},
{-1,0,0,-1,0,0,-1,0,0},
{0,-1,0,0,-1,0,0,-1,0},
{0,0,-1,0,0,-1,0,0,-1},
{-1,0,0,0,-1,0,0,0,-1},
{0,0,-1,0,-1,0,-1,0,0},
{1,0,0,0,0,0,0,0,0},
{0,1,0,0,0,0,0,0,0},
{0,0,1,0,0,0,0,0,0},
{0,0,0,1,0,0,0,0,0},
{0,0,0,0,1,0,0,0,0},
{0,0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,1,0},
{0,0,0,0,0,0,0,0,1},
{-1,0,0,0,0,0,0,0,0},
{0,-1,0,0,0,0,0,0,0},
{0,0,-1,0,0,0,0,0,0},
{0,0,0,-1,0,0,0,0,0},
{0,0,0,0,-1,0,0,0,0},
{0,0,0,0,0,-1,0,0,0},
{0,0,0,0,0,0,-1,0,0},
{0,0,0,0,0,0,0,-1,0},
{0,0,0,0,0,0,0,0,-1}
};
b={15,15,15,15,15,15,15,15,-15,-15,-15,-15,-15,-15,-15,-15,9,9,9,9,9,9,9,9,9,-1,-1,-6,-1,-1,-1,-1,-1,-1};
LinearProgramming[-c,-m,-b]

{2, 7, 6, 9, 5, 1, 4, 3, 8}

Mathematica does find a solution in less than a second. An interesting ( Mathematica ) programming exercise would be to generate the code for solving this integer programming problem for magic squares of size n. With increasing n the number of constraints increase fast. This could become an interesting benchmark. - For a 3 by 3 magic square 34 constraints are used above ( although 32 would have sufficed, probably even less ) but these constraints can be systematically generated.

Tidak ada komentar:

Posting Komentar