Puzzles
Third-order magic square. Try to fill in a 3x3 table with these 9 different integers, making the sum of the numbers on each row, each column, and each diagonal 1~9.
Strategy
Exhaustive search. Lists all the integer fill schemes, and then filters them.
JavaScript solution
Copy Code code as follows:
/**
* Created by Cshao on 12/28/14.
*/
function Getpermutation (arr) {
if (arr.length = = 1) {
return [arr];
}
var permutation = [];
for (var i=0; i<arr.length; i++) {
var firstele = arr[i];
var Arrclone = Arr.slice (0);
Arrclone.splice (i, 1);
var childpermutation = getpermutation (Arrclone);
for (var j=0; j<childpermutation.length; J + +) {
Childpermutation[j].unshift (Firstele);
}
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[lin E*3+2];
}
Function Sumofcolumn (candidate, col) {
return Candidate[col] + candidate[col+3] + candidate[col+6];< br>}
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<permutation.length; i++) {
candidate = Permutation[i];
if (Validatecandidate (candidate)) {
Break
} else {
candidate = null;
}
}
if (candidate) {
Console.log (candidate);
} else {
Console.log (' No valid result found ');
}
Results
Copy Code code as follows:
[2, 7, 6, 9, 5, 1, 4, 3, 8]
Depicted as a magic square is:
Copy Code code as follows:
Analysis
Using this strategy, we can theoretically obtain the solution of any n-order magic square, but in fact we can only get the 3-order magic square, because when n>3, it will be extremely time-consuming to get all the fill schemes.