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.
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):
# Write your code here
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]
]
input = [number for row in s for number in row]
mincost = float('inf')
for square in magic_squares:
cost = sum(abs(a - b) for a,b in zip(input, square))
if cost < mincost:
mincost = cost
return mincost
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Forming a Magic Square
You are viewing a single comment's thread. Return to all comments →
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):