Puzzle
Third-order magic square. Try filling 9 different integers from 1 to 9 into a 3×3 table so that the sum of the numbers in each row, column and diagonal is the same.
Strategy
Exhaustive search. List all integer padding scenarios, then filter.
JavaScript Solution
function getPermutation(arr) {
if (arr.length == 1) {
Return [arr];
}
var permutation = [];
for (var i=0; i
var arrClone = arr.slice(0);
arrClone.splice(i, 1);
var childPermutation = getPermutation(arrClone);
for (var j=0; j
}
Permutation = permutation.concat(childPermutation);
}
Return permutation;
}
function validateCandidate(candidate) {
var sum = candidate[0] candidate[1] candidate[2];
for (var i=0; i<3; i ) {
If (!(sumOfLine(candidate,i)==sum && sumOfColumn(candidate,i)==sum)) {
Return false;
}
}
if (sumOfDiagonal(candidate,true)==sum && sumOfDiagonal(candidate,false)==sum) {
Return true;
}
return false;
}
function sumOfLine(candidate, line) {
return candidate[line*3] candidate[line*3 1] candidate[line*3 2];
}
function sumOfColumn(candidate, col) {
return candidate[col] candidate[col 3] candidate[col 6];
}
function sumOfDiagonal(candidate, isForwardSlash) {
return isForwardSlash ? candidate[2] candidate[4] candidate[6] : candidate[0] candidate[4] candidate[8];
}
var permutation = getPermutation([1,2,3,4,5,6,7,8,9]);
var candidate;
for (var i=0; i
if (validateCandidate(candidate)) {
Break;
} else {
candidate = null;
}
}
if (candidate) {
console.log(candidate);
} else {
console.log('No valid result found');
}
Results
is depicted as a magic square:
Analysis
Using this strategy, you can theoretically obtain the solution to any n-order magic square, but in fact you can only obtain the specific solution of the 3rd-order magic square, because when n>3, the exhaustive operation of obtaining all filling solutions is The time consuming will be extremely huge.