Puzzles
Third-order magic Square (nine Sudoku). 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.
Policy
Exhaustive search. Lists all the integer fill schemes, and then filters them.
JavaScript Solution
The code is as follows |
Copy Code |
/** * 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[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<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
[2, 7, 6, 9, 5, 1, 4, 3, 8]
Depicted as a magic square is:
2 7 6
9 5 1
4 3 8
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.