We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Forming a Magic Square
Forming a Magic Square
Sort by
recency
|
1201 Discussions
|
Please Login in order to post a comment
I had to follow the tips people gave in the discussions about there only being 8 different 3x3 magic squares. For a start I did not even know the concept of a magic square and it took me a while to realize that the sums must equal 15. Anyhow, here is a solution in C, definitely not the most optimized but it's the best I could manage right now.
JavaScript
The key here is to know that only 8 possible magic squares are possible with a 3x3 matrix having numbers 1-9. If this is not known we can still find the constand by adding 1-9 (45) and dividing it by 3(number of rows) to get the constant 15. So instead of creating a function to find lowest cost magic square for any given input of 's' we need to instead compare the given 's' with the possible 8 magic squares.
My solution below :
def formingMagicSquare(s):
Using python
magic_squares = [ [8,1,6,3,5,7,4,9,2], [6,1,8,7,5,3,2,9,4], [4,9,2,3,5,7,8,1,6], [2,9,4,7,5,3,6,1,8], [8,3,4,1,5,9,6,7,2], [4,3,8,9,5,1,2,7,6], [6,7,2,1,5,9,8,3,4], [2,7,6,9,5,1,4,3,8], ] s_flat = [s[i][j] for i in range(3) for j in range(3)] min_cost = float('inf') for magic in magic_squares: cost = sum(abs(s_flat[i] - magic[i]) for i in range(9)) if cost < min_cost: min_cost = cost return min_cost