# Magic Square

## Hackerrank: Forming a magic Square

I must admit that this problem actually took me a good while to solve. Once you have the right insight on forming a magic Square it is really straight forward. But until that point I was just stuck. Anyway, before rambling on lets get to the actual problem.

We define a magic square to be an $n \times n$ matrix of distinct positive integers from 1 to nwhere the sum of any row, column, or diagonal (of length n) is always equal to the same number (i.e., the magic constant).

Consider a $3 \times 3$ matrix, s, of integers in the inclusive range [1, 9]. We can convert any digit, a, to any other digit, b, in the range [1, 9] at cost $\lvert a - b\rvert$.

Given , convert it into a magic square at minimal cost by changing zero or more of its digits. Then print this cost on a new line.

Note: The resulting magic square must contain distinct integers in the inclusive range [1, 9].

Posted by Kristian in HackerRank, 2 comments