Problem Statement
/*
stevevai has seen this
*/
PROBLEM STATEMENT
You are given an int[] of 9 non negative integers. You are to find out if these
numbers can be arranged to form a 3x3 Magic Square, and if so, output its Magic
Sum.
A 3x3 Magic Square is a 2-dimensional matrix with 3 rows and 3 columns, such
that the sum of the elements in each row, each column and each diagonal is the
same. This sum is called Magic Sum.
From now on Magic Square implies 3x3 Magic Square.
For Example
-------
|8|1|6|
-------
|3|5|7|
-------
|4|9|2|
-------
The above is a Magic Square as,
Sum of each row = (8+1+6) = (3+5+7) = (4+9+2) = 15
Sum of each column = (8+3+4) = (1+5+9) = (6+7+2) =15
Sum of each diagonal = (8+5+2) = (6+5+4) = 15
i.e. Magic Sum = 15
Create a class MagicSqr that contains a method magicSum, which takes int[] as
input and returns an int containing the Magic Sum of the Magic Square formed
from the elements of the input.
DEFINITION
Class: MagicSqr
Parameters: int[]
Returns: int
Method signature (be sure your method is public): int magicSum(int[] magicNums)
NOTES
- If no Magic Square can be formed from the input, return -1.
- Each element from the input has to be used in the Magic Square.
- There can be multiple elements in the input int[] which have the same value.
In such a case this value should appear exactly as many times in the Magic
Square as in the input.
- It is given that all possible Magic Squares for a given input will have the
same Magic Sum.
TopCoder will ensure the validity of the inputs. Inputs are valid if all of
the following criteria are met:
- Input parameter magicNums contains exactly 9 integers.
- Each element of the input parameter magicNums is between 0 and 100, inclusive.
EXAMPLES
Example 1:
magicNums = {1,2,3,4,5,6,7,8,9}
A Magic Square can be formed as
-------
|8|1|6|
-------
|3|5|7|
-------
|4|9|2|
-------
hence your method should return 15.
Example 2:
magicNums = {1,1,1,1,1,1,1,1,1}
A Magic Square can be formed as
-------
|1|1|1|
-------
|1|1|1|
-------
|1|1|1|
-------
hence your method should return 3.
Example 3:
magicNums = {16,14,12,12,10,8,8,6,4}
A Magic Square can be formed as
----------
|12| 4|14|
----------
|12|10| 8|
----------
|6 |16| 8|
----------
hence your method should return 30.
Example 4:
magicNums = {1,1,1,1,5,1,1,1,1}
No Magic Square is possible, hence your method returns -1.Definition
- Class:
- MagicSqr
- Method:
- magicSum
- Parameters:
- int[]
- Returns:
- int
- Method signature:
- int magicSum(int[] param0)
- (be sure your method is public)
Constraints
Examples
No public sample cases were explicitly marked for this problem in the original data.