Advertisement
Mussab_Blue

Magic Square

Jul 15th, 2022 (edited)
585
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. grid = [[54,12 , 0, 0],
  2.         [0, 39, 0, 30],
  3.         [33,27,24, 42],
  4.         [18, 0, 0, 0 ]]
  5. w = len(grid) #height or width
  6.  
  7. #instructions to dynamically generate rows, columns, diagonals coords
  8. dirs = {i:[(w,1)[not i%w]] for i in range(w*w) if i<w or i%w==0} #rows, columns
  9. dirs[0].extend([w, w+1])
  10. dirs[w-1].append(w-1)  
  11.  
  12. def get_spot_coords(start, step): #generate row, column or diagonal coords
  13.     end = w * step + start
  14.     return [divmod(i,w) for i in range(start, end, step)]
  15.  
  16. target = 0 #target sum
  17. for start in dirs.keys():
  18.     for step in dirs[start]:
  19.         temp = [grid[x][y] for x,y in get_spot_coords(start, step)]
  20.         if temp.count(0)==0: target = sum(temp)
  21.  
  22. while not all(grid[i//w][i%w] > 0 for i in range(w*w)):
  23.     for start in dirs.keys():
  24.         for step in dirs[start]:
  25.             spot = get_spot_coords(start, step)
  26.             if sum(grid[x][y]>0 for x, y in spot) == w-1:
  27.                 x, y = [(x,y) for x,y in spot if grid[x][y]==0][0]
  28.                 grid[x][y] = target - sum(grid[i][j] for i,j in spot)
  29. print(*grid, sep='\n')
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement