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
- Discussions
Forming a Magic Square
Forming a Magic Square
Sort by
recency
|
38 Discussions
|
Please Login in order to post a comment
Idk why all the python answers assume you'd have access to a list of all magic squares when doing this problem.I guess to game the hackerrank rankings? Not very helpful for people actually trying to learn. Anyways, Here's how I would solve this on an actual test, including code to find all magic squares:
I have no clue how you supossed to figure this out on your own without serious matrix theory knowladge, and the knowladge of this silly trivia magic array, here is the info: There are fixed 9 numbers in 3x3 magic array, there is no other choice. Thje example gives this. The only different arrays can either 90 degree rotations of this magic array. Or a reflection on the middle, then this can also be rotated 90 degrees 3 times to get different versions. Good luck figuring this out on an interview.. ???
int matrix_diff(vector>& A, vector>& B){ int diff=0; for(int i=0;i
void transpose(vector>& A){ for(int i=0; i
void reflect(vector>& A){ for(int i=0; i
int formingMagicSquare(vector> s) { std::vector> magic = {{8,3,4},{1,5,9},{6,7,2}}; //there is only one magic array, and its 8 versions, by 3* 90degree rotation, then 1 reflection and 3rotations again //make another version, then compare diff to s, and record minimum; int min_global_diff=matrix_diff(s, magic);
}
Python 3:
Solution in CPP, building all magic squares:
Not as bad a question as some people here make out.
Generate all permutations of list [1,2,3,4,5,6,7,8,9] (the list is a flattened square 3x3 2D array)
Filter for lists that are magic (the criteria are in the question)
Calculate distance from input array to each magic square
Return minimum distance