使用JavaScript實現九宮格演算法解答

來源:互聯網
上載者:User

謎題

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

策略

窮舉搜尋。列出所有的整數填充方案,然後進行過濾。

JavaScript解

 代碼如下 複製代碼

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


結果

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

描繪成幻方即為:

2    7    6
9    5    1
4    3    8

分析


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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.