JavaScript实现三阶幻方算法谜题解答
谜题
三阶幻方。试将1~9这9个不同整数填入一个3×3的表格,使得每行、每列以及每条对角线上的数字之和相同。
策略
穷举搜索。列出所有的整数填充方案,然后进行过滤。
JavaScript解
/** *Createdbycshaoon12/28/14. */
functiongetPermutation(arr){ if(arr.length==1){ return[arr]; }
varpermutation=[]; for(vari=0;i<arr.length;i++){ varfirstEle=arr[i]; vararrClone=arr.slice(0); arrClone.splice(i,1); varchildPermutation=getPermutation(arrClone); for(varj=0;j<childPermutation.length;j++){ childPermutation[j].unshift(firstEle); } permutation=permutation.concat(childPermutation); } returnpermutation; }
functionvalidateCandidate(candidate){ varsum=candidate[0]+candidate[1]+candidate[2]; for(vari=0;i<3;i++){ if(!(sumOfLine(candidate,i)==sum&&sumOfColumn(candidate,i)==sum)){ returnfalse; } } if(sumOfDiagonal(candidate,true)==sum&&sumOfDiagonal(candidate,false)==sum){ returntrue; } returnfalse; } functionsumOfLine(candidate,line){ returncandidate[line*3]+candidate[line*3+1]+candidate[line*3+2]; } functionsumOfColumn(candidate,col){ returncandidate[col]+candidate[col+3]+candidate[col+6]; } functionsumOfDiagonal(candidate,isForwardSlash){ returnisForwardSlash?candidate[2]+candidate[4]+candidate[6]:candidate[0]+candidate[4]+candidate[8]; }
varpermutation=getPermutation([1,2,3,4,5,6,7,8,9]); varcandidate; for(vari=0;i<permutation.length;i++){ candidate=permutation[i]; if(validateCandidate(candidate)){ break; }else{ candidate=null; } } if(candidate){ console.log(candidate); }else{ console.log('Novalidresultfound'); }