# Problem of the DayA new programming or logic puzzle every Mon-Fri

## Magic Square

A magic square is an NxN grid where all columns, rows, and diagonals add to the same number. In the case of diagonals on top corner to opposite bottom corner count. Can you create a function that takes in an NxN array and returns if that array is a magic square or not? An example of a 3x3 magic square is below:

```4  9  2
3  5  7
8  1  6
```

• - 8 years, 1 month ago

Quick and dirty python

``````def magicSquareTest(grid):
return (rowsPass(grid) and colsPass(grid) and diagsPass(grid))

def colsPass(grid):
return rowsPass(transpose(grid))

def diagsPass(grid):
return rowsPass(getDiagRows(grid))

def rowsPass(grid):
return len({(sum(row)) for row in grid})==1

def getDiagRows(grid):
r1 = list()
r2 = list()
length=len(grid)-1
for i in range(length+1):
r1.append(grid[i][i])
r2.append(grid[i][length-i])
return [r1,r2]

def transpose(grid):
return list(map(list,zip(*grid)))

if __name__=='__main__':
grid1 = [[4, 9, 2], [3, 5, 7], [8, 1, 6]]
grid2 = [[4, 9, 2], [3, 1, 7], [8, 1, 6]]
print(magicSquareTest(grid))
print("Testing grid: ")
print(grid1)
print(magicSquareTest(grid1))
print("Testing grid: ")
print(grid2)
print(magicSquareTest(grid2))
``````
• Max Burstein - 8 years, 1 month ago

Nicely done!

Content curated by @MaxBurstein