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
|
1260 Discussions
|
Please Login in order to post a comment
Here is problem solution in Python, Java, C++, C and Javascript - https://programmingoneonone.com/hackerrank-forming-a-magic-square-problem-solution.html
for matrix 6 1 2 7 2 6 5 6 2
cost is coming as 18 but it should be 20 as most economical transformation will be
6 1 8 7 5 3 2 9 4
Forming a magic square is a fascinating mathematical exercise that involves arranging numbers in a square grid so that the sums of the numbers in each row, column, and both main diagonals are all the same. This constant sum is known as the magic constant or magic sum. Typically, a magic square uses a set of consecutive integers starting from 1. The simplest magic square royal dream x8 is a 3x3 grid, and it has a magic constant of 15 when filled with numbers 1 to 9. Constructing a magic square requires logical thinking, attention to pattern, and sometimes specific techniques depending on whether the square has an odd, even, or doubly even number of rows and columns.
The Fastest, concise, and most straight-forwarded Solution You will ever find across all discussion:
include
using namespace std;
int main(){ int magic_sqr[8][9] = { {8,1,6,3,5,7,4,9,2}, {6,1,8,7,5,3,2,9,4}, {4,3,8,9,5,1,2,7,6}, {8,3,4,1,5,9,6,7,2}, {2,9,4,7,5,3,6,1,8}, {4,9,2,3,5,7,8,1,6}, {6,7,2,1,5,9,8,3,4}, {2,7,6,9,5,1,4,3,8} };
}
I came to the same solution in TypeScript, except without serialising the matrix s. I think this is the only comprehensive solution.
Could I get clarification? I implemented a code and found the cost lower than the one in the example for a new matrix. For the given matrix:
4 8 2
4 5 7
6 1 6
The matrix below solves it at a lower cost (this is what my code found):
[4, 8, 2]
[4, 4, 6] = cost is 2
[6, 2, 6] = cost is 1
The magic constant is 14 and The cost is 3
sum of rows and columns and diagonals for magic square is 15 not 14, also you cannot repeat numbers
its not mentioned as 15, so u can take anything as the sum
The diagonal does not add up to 14. 6 + 4 + 2 = 12.