6 kyu

Forming a Magic Square

Description:

Define

We define a magic square to be an n x n matrix of distinct positive integers from 1 to n^2 to where the sum of any row, column, or diagonal of length is always equal to the same number: the magic constant.


Assesment

You will be given a 3 x 3 matrix 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 of |a-b|(the absolute of the amount changed). Given s, convert it into a magic square at minimal cost. Return this cost.

Example 1:

Given s:

5 3 4

1 5 8

6 4 2

We can convert it to the following magic square:

8 3 4

1 5 9

6 7 2

This took three replacements at a cost of |5-8| + |8-9| + |4-7| = 7.

The formingMagicSquare function should return an integer that represents the minimal total cost of converting the input square to a magic square.


Input

An array of each row with an array of each number. [ [], [], [] ]

Output

Return an integer denoting the minimum cost of turning the matrix into a magic square.

Example 2:

Given s:

4 9 2

3 5 7

8 1 5

Output is: 1

Since changing s[2][2] from 5 to 6 makes this a magic square and |5-6| = 1.


to get you started, ask yourself how many possible magic squares can exist?.
Algorithms
Fundamentals

More By Author:

Check out these other kata created by copyrightbreaker

Stats:

CreatedOct 21, 2018
PublishedOct 21, 2018
Warriors Trained416
Total Skips53
Total Code Submissions397
Total Times Completed68
JavaScript Completions42
Java Completions29
Total Stars15
% of votes with a positive feedback rating93% of 22
Total "Very Satisfied" Votes19
Total "Somewhat Satisfied" Votes3
Total "Not Satisfied" Votes0
Total Rank Assessments6
Average Assessed Rank
6 kyu
Highest Assessed Rank
5 kyu
Lowest Assessed Rank
7 kyu
Ad
Contributors
  • copyrightbreaker Avatar
  • G_kuldeep Avatar
Ad