Forming a Magic Square JavaScript Solution

Megan
1 min readMar 24, 2022

For today’s algorithm, we are solving HackerRank’s forming a magic square problem. A magic square is a matrix of distinct positive integers from to where the sum of any row, column, or diagonal of length is always equal to the same number: the magic constant. All tests are for a 3x3 square. 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45. 45 / 3 =15. Our magic constant is 15.

Since there are only 8 possible combinations to get our magic constant, we will make it a constant variable, n. We will also make a variable of an array of 8 arrays of 0, arr.

Then, we will loop through the magic array and compare it to the s matrix and find the differences. Every time isEven is true, we execute the loop, switch the values in the forEach loop, and then for the next iteration we scramble our S matrix to test another version.

--

--