Searching for a 3x3 Magic Square

September 2004
Demo for "intro programming"
Jim Mahoney

I'll just use a list of the numbers for the square

square = Range[0, 8]

magicQ::usage = "magicQ[{0,1,2,3,4,5,6,7,8}] returns True if the \
list contains the numbers in a 3x3 magic square.";
magicQ[square_] := 
        Module[{answer}, 
 (* 
            This version only works for 3  
              x3 magic squares
 
              which are input as a list of 9 numbers .   indeces are, 
1 2 3, 
4 5 6, 
7 8 9 
*) 
lines  =  {
{1, 2, 3}, {4, 5, 6}, {7, 8, 9},     (* 
                rows *) 
{1, 4, 7}, {2, 5, 8}, {3, 6, 
                9},    (* columns *) 
{1, 5, 9}, {3, 5, 
                7}};                           (* 
            diagonals *) 
number  =  
            square[[1]] + square[[2]] + 
              square[[3]]; 
answer = True;   (* 
            defult,  
            if we pass all tests *) 
Do[ 
  If[
              Total[square[[lines[[i]]]]] ≠ number, 
              answer = False], 
{i, 1, 
              8}
]; 
Return[
            answer]; 
];

allSquares = Permutations[Range[0, 8]];

allSquares[[1]]

allSquares[[2]]

(* 
      Search over all permuations for a 3  x 3 that' 
        s a magic square *) 
Do[
If[magicQ[allSquares[[i]]], 
        Print[allSquares[[i]]]], 
{i, 1, 
        Length[allSquares]}
]

ans = {1, 6, 5, 8, 4, 0, 3, 2, 7};

MatrixForm[
      Table[ans[[{i, i + 1, i + 2}]], {i, 1, 7, 3}]]