← Back to challenges

Magic Square Gen

PythonHardalgorithmsarraysgeometrygames

Instructions

Make a function that takes a integer, size, returns 2D list that is a Magic Square with side lengths of size

A Magic Square is an arrangement of numbers in a square in such a way that the sum of each row, column, and diagonal is one constant number, the "magic constant." For this challenge I will be testing with the assumption that your magic squares are made with whole numbers from 1 - n^2

Example

make_magic(3) ➞ [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
# Rows: 2+7+6 = 9+5+1 = 4+3+8 = 15
# Columns: 2+9+4 = 7+5+3 = 6+1+8 = 15
# Diagonals: 2+5+8 = 6+5+4 = 15

Notes

For this challenge I will only be testing with sizes >= 3 as there are no Magic Squares of size 2 at least as I have described them.

python3
Loading editor…
to run
Walks through the solution with reasoning and edge cases.