Search code examples
pythonmagic-square

Magic Squares - Siamese Method


Is it possible to do magic squares with the Siamese/De La Loubere method without using modulo?

I would like to make odd n x n magic squares using it.


Solution

  • Yes, it's possible. Written on Python 3.5:

    def siamese_method(n):
    
        assert(n % 2 != 0), 'Square side size should be odd!'
        square = [[0 for x in range(n)] for x in range(n)]
        x = 0
        y = int((n + 1) / 2 - 1)
        square[x][y] = 1
    
        for i in range(2, n * n + 1):
            x_old = x
            y_old = y
    
            if x == 0:
                x = n - 1
            else:
                x -= 1
    
            if y == n - 1:
                y = 0
            else:
                y += 1
    
            while square[x][y] != 0:
                if x == n - 1:
                    x = 0
                else:
                    x = x_old + 1
                y = y_old
    
            square[x][y] = i
    
        for j in square:
            print(j)
    
    
    siamese_method(3)
    

    I've got following on output:

    [8, 1, 6]
    [3, 5, 7]
    [4, 9, 2]