Home  >  Article  >  Web Front-end  >  JavaScript implements third-order magic square algorithm puzzle solution_javascript skills

JavaScript implements third-order magic square algorithm puzzle solution_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:23:441962browse

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

Copy code 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');
}

Results


Copy code The code is as follows:

[ 2, 7, 6, 9, 5, 1, 4, 3, 8 ]

is depicted as a magic square:


Copy code The code is as follows:

2 7 6
9 5 1
4 3 8

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn