HomeHome More SamplesMore Samples

///////////////////////////////////////////////////////////////////////////////
//
// An associative magic square is a magic square for which every pair of numbers 
// symmetrically opposite to the center sum up to the same value n*n + 1 
//
// This program calculates all 48544 solutions (solutions without rotational and 
// reflective symmetry). 
//
//
///////////////////////////////////////////////////////////////////////////////
//
// To generate all 48544 solutions, run query: 
//
//      all MagicSquares5x5Associative()
//
// To generate a single solution, run query: 
//
//      one MagicSquares5x5Associative()
//
// You may want to generate only a subset of all magic squares, for example
// to generate only 100 solutions, use the following query:
//
//     all MagicSquares5x5Associative() & RtlTrimSolutions(100)
//
///////////////////////////////////////////////////////////////////////////////

pred MagicSquares5x5Associative() iff    // u = 65
    ms::[0..24]->>L[1..25] &
    ms = [ a1, a2, a3, a4, a5,
           b1, b2, b3, b4, b5,
           c1, c2, c3, c4, c5,
           d1, d2, d3, d4, d5,
           e1, e2, e3, e4, e5
         ] &

    // Remove symmetries

    a1 < a5 & a1 < e1 & a1 < e5 & a5 < e1 & 

    // Constraint all symmetrically opposite numbers 

    b3 + d3 = 26 &
    c2 + c4 = 26 &
    a3 + e3 = 26 &
    c1 + c5 = 26 &
    b2 + d4 = 26 &
    a1 + e5 = 26 &
    d2 + b4 = 26 &
    e1 + a5 = 26 &

    a2 + e4 = 26 & 
    b1 + d5 = 26 &
    a4 + e2 = 26 & 
    b5 + d1 = 26 &

    // Standard constraints for Magic Square 5x5

    a1 + b2 + c3 + d4 + e5 = 65 &  
    e1 + d2 + c3 + b4 + a5 = 65 & 

    a1 + a2 + a3 + a4 + a5 = 65 &
    a1 + b1 + c1 + d1 + e1 = 65 &

    b1 + b2 + b3 + b4 + b5 = 65 &
    a2 + b2 + c2 + d2 + e2 = 65 &
    
    c1 + c2 + c3 + c4 + c5 = 65 &
    a3 + b3 + c3 + d3 + e3 = 65 &
    
    d1 + d2 + d3 + d4 + d5 = 65 &
    a4 + b4 + c4 + d4 + e4 = 65 &
    
    e1 + e2 + e3 + e4 + e5 = 65 &
    a5 + b5 + c5 + d5 + e5 = 65 & 
    PrettyPrint(ms,0)


///////////////////////////////////////////////////////////////////////////////
local proc PrettyPrint(ms:<[0..24]->>L[1..25], row:<I) iff
    if row < 5 then
        j = row*5 &
        Print('\n') &
        PrintDigit(ms(j)) &
        PrintDigit(ms(j+1)) &
        PrintDigit(ms(j+2)) &
        PrintDigit(ms(j+3)) &
        PrintDigit(ms(j+4)) &
        PrettyPrint(ms,row+1)
    else
        Print('\n') 
    end

local proc PrintDigit(d:<L) iff
    if d < 10 then
        Print(' ',d,' ')
    else
        Print(d,' ')
    end








This page was created by F1toHTML