This article describes how to implement the third-level magic square algorithm in JavaScript ~ 9 fill in the 9 different integers in a 3 & #215; 3 table, so that the sum of numbers on each row, column, and each diagonal line is the same. For more information, see
Puzzles
Level 3 magic. Try 1 ~ 9 fill in the nine different integers in a 3 × 3 table, so that the sum of numbers on each row, column, and each diagonal line is the same.
Policy
Search without question. List all integer filling schemes and filter them.
JavaScript Solution
The Code is 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 var firstEle = arr [I];
Var arrClone = arr. slice (0 );
ArrClone. splice (I, 1 );
Var childPermutation = getPermutation (arrClone );
For (var j = 0; 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 [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 Candidate = permutation [I];
If (validateCandidate (candidate )){
Break;
} Else {
Candidate = null;
}
}
If (candidate ){
Console. log (candidate );
} Else {
Console. log ('no valid result found ');
}
Result
The Code is as follows:
[2, 7, 6, 9, 5, 1, 4, 3, 8]
Depicted as magic:
The Code is as follows:
2 7 6
9 5 1
4 3 8
Analysis
In theory, this policy can be used to obtain the solution of any level n magic, but in fact it can only obtain the Level 3 magic, because when n> 3, retrieving all filling schemes will take a huge amount of time.