-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkMagicSquare.js
56 lines (55 loc) · 1.5 KB
/
checkMagicSquare.js
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
function checkMagicSquare(n, matrix) {
// let sumArr = []
// let mainDiagonalSum = 0
// let diagonalSum = 0
// let sum=0
// for (let i = 0; i < n; i++) {
// let rowSum = 0
// let columnSum = 0
// for (let j = 0; j < n; j++) {
// rowSum += matrix[i][j]
// columnSum += matrix[j][i]
// }
// sumArr.push(rowSum)
// sumArr.push(columnSum)
// }
// for (let k=0; k<n; k++){
// mainDiagonalSum += matrix[k][k]
// }
// for (let k = n - 1; k >= 0; k--) {
// diagonalSum += matrix[n-k-1][k]
// }
// sumArr.push(mainDiagonalSum)
// sumArr.push(diagonalSum)
// for (let i=0; i<sumArr.length; i++){
// sum+=sumArr[i]
// }
// return (sum===sumArr[0]*sumArr.length)
let mainDiagonalSum = 0
let diagonalSum=0
for (let i=0; i<n; i++){
mainDiagonalSum += matrix[i][i]
diagonalSum+=matrix[i][n-i-1]
}
if (diagonalSum!==mainDiagonalSum){
return false
}
for (let i = 0; i < n; i++) {
let rowSum = 0
let columnSum = 0
for (let j = 0; j < n; j++) {
// if (i+j===n-1){
// diagonalSum+=matrix[i][j]
// }
rowSum += matrix[i][j]
columnSum += matrix[j][i]
}
if (rowSum!==mainDiagonalSum || columnSum!==mainDiagonalSum){
return false
}
}
// if (diagonalSum!==mainDiagonalSum){
// return false
// }
return true
}