• + 5 comments

    It helps to know (from wiki [1] and YouTube video [2]) there are 8 possible 3x3 magic squares. Each can be obtained by a rotation or reflection (or combination of) of each other.

    If you define a starting magic square, you can perform the following relatively simple transormations to obtain all 8 squares:

    M # Starting square
    rotate(M) # rotate clockwise 90 degrees
    rotate(rotate(M)) # rotate clockwise 180 degrees
    rotate(rotate(rotate(M))) # rotate clockwise 270 degrees
    refect(M,dim=rows) # reflect along row dimension
    reflect(M,dim=cols) # reflect along column dimension
    reflect(M,dim=diag) # reflection along main diagonal
    transpose(M) # reflect along off-diagonal
    

    You have to define these functions, but atleast they're quite simple and you don't have to search all possible permutations.

    A useful YouTube video is 'SOLVE The 3x3 Magic Square Completely - There Can Only Be One!'

    [1] https://en.wikipedia.org/wiki/Magic_square

    [2] https://www.youtube.com/watch?v=zPnN046OM34