-
Notifications
You must be signed in to change notification settings - Fork 9
/
MagicSquare.java
92 lines (92 loc) · 2.37 KB
/
MagicSquare.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//*******************************************************
// MagicSquare.java
// The class represent a MazicSquare
// Author: liron mizrahi
//*******************************************************
public class MagicSquare
{
/**
* method return the sum of given row in the mat
* @parm int[][] mat, int rowNumber
* @return int
*/
public static int sumRow(int[][] mat, int rowNumber)
{
int sum = 0;
for (int i = 0; i < mat[rowNumber].length; i++)
{
sum += mat[rowNumber][i];
}
return sum;
}// end of method sumRow
/**
* method return the sum of given col in the mat
* @parm int[][] mat, int colNumber
* @return int
*/
public static int sumCol(int[][] mat, int colNumber)
{
int sum = 0;
for (int i = 0; i < mat.length; i++)
{
sum += mat[i][colNumber];
}
return sum;
}// end of method sumCol
/**
* method return the sum of the primary digonal
* @parm int[][] mat
* @return int
*/
public static int sumPrimaryDiag(int[][] mat)
{
int sum = 0;
for (int i = 0; i < mat.length; i++)
{
sum += mat[i][i];
}
return sum;
}// end of method sumPrimaryDiag
/**
* method return the sum of the second digonal
* @parm int[][] mat
* @return int
*/
public static int sumSecondaryDiag(int[][] mat)
{
int sum = 0;
for (int i = 0; i < mat.length; i++)
{
sum += mat[i][mat.length-1-i];
}
return sum;
}// end of method sumSecondaryDiag
/**
* method return true if given int[][] is magicsquare otherwise return false
* @parm int[][] mat
* @return boolean
*/
public static boolean isMagicSquare(int[][] mat)
{
int sumRow;
int sumCol;
int sumPrimary = sumPrimaryDiag(mat);
int sumSecondary = sumSecondaryDiag(mat);
if(sumPrimary != sumSecondary)
{
return false;
}
for(int i = 0; i < mat.length; i++)
{
if(sumRow(mat, i) != sumPrimary)
{
return false;
}
if(sumCol(mat, i) != sumPrimary)
{
return false;
}
}
return true;
}// end of method isMagicSquare
}// end of class MagicSquare