Monday, February 23, 2015

py26. Magic Function in Python

Magic matrices have sum of all rows and sum of all columns equal to some number. In addition, the sum of the primary and secondary cross diagonal equal that number, called the magic number. The magic number is only dependent on size of matrix.


The program will solve magic matrices for odd size, such as 11 by 11 (N = 11).


For a magic matrix, such as a size of 11 by 11, we have elements from 1 to 11 square. The magic number is the mean of all elements from 1 to N square, multiplied by N.


We use the numpy.zeros function to create a N*N matrix and then loop, over the 2-dimensions, to get the individual elements, {1,2,3,...N^2}, into their correct positions. Magic matrices are not unique, there are many others, dependent on the algorithm, with the same sum property, however the magic number for a particular N is unique.


Lastly, we check all the relevant sums.

# ex26.py
from __future__ import print_function, division
import numpy as np

N = 11

magic_num = sum(range(1,N**2+1))/N

def mat(i,j):
    i = i % N
    j = j % N
    return i,j
    
A = np.zeros((N,N))
st = (N-1)/2,(N+1)/2

for k2 in range(N):
    st = st[0]+1,st[1]-1
    for k in range(N):
        A[mat(st[0]+k,st[1]+k)] = k+k2*N+1

A = A.astype('int')
AR = np.fliplr(A)
print('magic(%d) = \n%s' % (N,A))
print('\nmagic number = %d' % magic_num)
print('sum primary diag = %d' % sum(A.diagonal()))
print('sum secondary diag = %d' % sum(AR.diagonal()))
for k2 in range(N):
    print('sum row %d = %d' % (k2,sum(A[k2,:])))
    print('sum col %d = %d' % (k2,sum(A[:,k2])))

#magic(11) = 
#[[ 56 117  46 107  36  97  26  87  16  77   6]
# [  7  57 118  47 108  37  98  27  88  17  67]
# [ 68   8  58 119  48 109  38  99  28  78  18]
# [ 19  69   9  59 120  49 110  39  89  29  79]
# [ 80  20  70  10  60 121  50 100  40  90  30]
# [ 31  81  21  71  11  61 111  51 101  41  91]
# [ 92  32  82  22  72   1  62 112  52 102  42]
# [ 43  93  33  83  12  73   2  63 113  53 103]
# [104  44  94  23  84  13  74   3  64 114  54]
# [ 55 105  34  95  24  85  14  75   4  65 115]
# [116  45 106  35  96  25  86  15  76   5  66]]
#
#magic number = 671
#sum primary diag = 671
#sum secondary diag = 671
#sum row 0 = 671
#sum col 0 = 671
#sum row 1 = 671
#sum col 1 = 671
#sum row 2 = 671
#sum col 2 = 671
#sum row 3 = 671
#sum col 3 = 671
#sum row 4 = 671
#sum col 4 = 671
#sum row 5 = 671
#sum col 5 = 671
#sum row 6 = 671
#sum col 6 = 671
#sum row 7 = 671
#sum col 7 = 671
#sum row 8 = 671
#sum col 8 = 671
#sum row 9 = 671
#sum col 9 = 671
#sum row 10 = 671
#sum col 10 = 671

No comments:

Post a Comment