function
* permutations(lst) {
if
(lst.length <= 1) yield lst;
else
{
for
(let perm of permutations(lst.slice(1))) {
for
(let i = 0; i < lst.length; i++) {
yield perm.slice(0, i).concat([lst[0]]).concat(perm.slice(i));
}
}
}
}
function
is_magic_square(lst) {
const a = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
for
(let i = 0; i < 3; i++) {
for
(let j = 0; j < 3; j++) {
a[i][j] = lst[3 * i + j];
}
}
const s = a[0].reduce((acc, val) => acc + val, 0);
for
(let i = 1; i < 3; i++) {
const tmp = a[i].reduce((acc, val) => acc + val, 0);
if
(tmp !== s) {
return
false
;
}
}
for
(let j = 0; j < 3; j++) {
const tmp = a.reduce((acc, row) => acc + row[j], 0);
if
(tmp !== s) {
return
false
;
}
}
const tmp1 = a[0][0] + a[1][1] + a[2][2];
if
(tmp1 !== s) {
return
false
;
}
const tmp2 = a[0][2] + a[1][1] + a[2][0];
if
(tmp2 !== s) {
return
false
;
}
return
true
;
}
function
find_magic_squares() {
const magic_squares = [];
const lst = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for
(let v of permutations(lst)) {
if
(is_magic_square(v)) {
magic_squares.push(v);
}
}
return
magic_squares;
}
function
diff(a, b) {
return
a.reduce((acc, val, idx) => acc + Math.abs(val - b[idx]), 0);
}
function
wrapper(v) {
let res = Infinity;
const magic_squares = find_magic_squares();
for
(let i = 0; i < magic_squares.length; i++) {
res = Math.min(res, diff(v, magic_squares[i]));
}
return
res;
}
const v = [4, 9, 2, 3, 5, 7, 8, 1, 5];
console.log(wrapper(v));