-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMagicSquare
More file actions
67 lines (52 loc) · 2.57 KB
/
Copy pathMagicSquare
File metadata and controls
67 lines (52 loc) · 2.57 KB
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
var s = [[4, 9, 2], [3, 5, 7], [8, 1, 5]];
// Complete the formingMagicSquare function below.
function formingMagicSquare(s) {
let magicSquare = [
[[8, 1, 6], [3, 5, 7], [4, 9, 2]],
[[6, 1, 8], [7, 5, 3], [2, 9, 4]],
[[4, 9, 2], [3, 5, 7], [8, 1, 6]],
[[2, 9, 4], [7, 5, 3], [6, 1, 8]],
[[8, 3, 4], [1, 5, 9], [6, 7, 2]],
[[4, 3, 8], [9, 5, 1], [2, 7, 6]],
[[6, 7, 2], [1, 5, 9], [8, 3, 4]],
[[2, 7, 6], [9, 5, 1], [4, 3, 8]],
];
///All permutations of 3*3 Magic Square
let arr = [];
let total = 0;
let min = 100; /// This min value is 100 bcoz it's greater than all sum 45 of each 3*3 magic Square. You can take any value to compare with min only condition is that it should be greater than 45.
for (let i = 0; i < 8; i++) {
arr.push(s);
}
/// Here we have created given s=>array matrix into 8*3*3 matrix equivalent to magicSquare 8*3*3.
/// Just push 8 times s=>array into arr=>array
///For eg. it will become
/*
[
[ [ 4, 9, 2 ], [ 3, 5, 7 ], [ 8, 1, 5 ] ],
[ [ 4, 9, 2 ], [ 3, 5, 7 ], [ 8, 1, 5 ] ],
[ [ 4, 9, 2 ], [ 3, 5, 7 ], [ 8, 1, 5 ] ],
[ [ 4, 9, 2 ], [ 3, 5, 7 ], [ 8, 1, 5 ] ],
[ [ 4, 9, 2 ], [ 3, 5, 7 ], [ 8, 1, 5 ] ],
[ [ 4, 9, 2 ], [ 3, 5, 7 ], [ 8, 1, 5 ] ],
[ [ 4, 9, 2 ], [ 3, 5, 7 ], [ 8, 1, 5 ] ],
[ [ 4, 9, 2 ], [ 3, 5, 7 ], [ 8, 1, 5 ] ]
]
*/
for (let i = 0; i < 8; i++) {
total = 0;
for (let j = 0; j < 3; j++) {
for (let k = 0; k < 3; k++) {
total = total + Math.abs(arr[i][j][k] - magicSquare[i][j][k]);
////Here I have compared each s=>array element and magicSquare=>array element, stored there difference in total variable.
}
}
if (total < min) {
min = total;
}
///Here each s=>array and magicSquare=> total is compared to min value
}
return min;
///Return minimum value amongst all comparisons that we had made between s=>array and magicSquaer=>array
}
console.log(formingMagicSquare(s));