最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript實現(xiàn)三階幻方算法謎題解答

 更新時間:2014年12月29日 09:38:00   投稿:junjie  
這篇文章主要介紹了JavaScript實現(xiàn)三階幻方算法謎題解答,三階幻方是指試將1~9這9個不同整數(shù)填入一個3×3的表格,使得每行、每列以及每條對角線上的數(shù)字之和相同,需要的朋友可以參考下

謎題

三階幻方。試將1~9這9個不同整數(shù)填入一個3×3的表格,使得每行、每列以及每條對角線上的數(shù)字之和相同。

策略

窮舉搜索。列出所有的整數(shù)填充方案,然后進(jìn)行過濾。

JavaScript解

復(fù)制代碼 代碼如下:

/**
 * 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');
}

結(jié)果


復(fù)制代碼 代碼如下:

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

描繪成幻方即為:


復(fù)制代碼 代碼如下:

2    7    6
9    5    1
4    3    8

分析

使用此策略理論上可以獲取任意n階幻方的解,但實際上只能獲得3階幻方這一特定解,因為當(dāng)n>3時,獲取所有填充方案這一窮舉操作的耗時將變得極其巨大。

相關(guān)文章

最新評論

泰宁县| 泉州市| 通州市| 维西| 星子县| 堆龙德庆县| 九寨沟县| 桐城市| 通山县| 武陟县| 上饶县| 乌审旗| 鸡东县| 宜兰县| 黎川县| 定边县| 昌都县| 漳州市| 开原市| 道孚县| 绥芬河市| 芦溪县| 皋兰县| 牡丹江市| 黄大仙区| 江陵县| 郯城县| 平和县| 任丘市| 绩溪县| 克拉玛依市| 建湖县| 固始县| 新邵县| 甘肃省| 屯留县| 丽水市| 安岳县| 湘西| 临海市| 察雅县|