JavaScript to solve the third-order magic Square (nine sudoku) _javascript skills

Source: Internet
Author: User

Puzzle: Third-order magic Square, try to fill in a 3x3 table with the 1~9 9 different integers, making the sum of the numbers on each row, each column, and each diagonal.

Strategy: Exhaustive search. Lists all the integer fill schemes, and then filters them.

The bright spot is the design of recursive function getpermutation, in the end, several non recursive algorithms are given.

Recursive algorithm, very clever, but too cost resource function getpermutation (arr) {if (arr.length = = 1) {return [arr];
  } var permutation = [];         for (var i = 0; i < arr.length i++) {var firstele = arr[i];      Take the first element var arrclone = arr.slice (0);         Copy array Arrclone.splice (I, 1); Delete the first element, reduce the array size var childpermutation = getpermutation (Arrclone);//recursive for (var j = 0; J < Childpermutation.leng Th   J + +) {childpermutation[j].unshift (Firstele);
  Insert the fetch element back} 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 sum Ofdiagonal (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 '); A specific example of a modulo (non-recursive) full array algorithm/* algorithm: * 4 Elements ["A", "B", "C", "D"], the entire arrangement, the total circulation 4!=24 times, can start from any >=0 integer index cycle, each cumulative 1, until the end of the cycle index+23; Suppose index=13 (or 13+24,13+224,13+3*24 ...). , because there are 4 elements, so the iteration is 4 times, the resulting arrangement is: * 1th iteration, 13/1, quotient =13, remainder = 0, so 1th element inserts No. 0 position (namely Subscript 0), get ["a"]; * 2nd iteration, 13/2, quotient =6, remainder = 1, so the 2nd element inserts 1th position (that is subscript 1), get ["A", "B"]; * 3rd iteration, 6/3,Quotient =2, remainder = 0, so 3rd element inserts No. 0 position (that is subscript 0), get ["C", "A", "B"]; * 4th iteration, 2/4, quotient =0, remainder = 2, so 4th element inserts 2nd position (namely Subscript 2), get ["C", "a", "D", "B"];
  function Perm (arr) {var result = new Array (arr.length);
  var FAC = 1;
    for (var index = 0; index < FAC; index++) {//each index corresponds to an array of var t = index;
      for (i = 1; I <= arr.length; i++) {//Determine the position of each number var w = t% i;
      for (var j = i-1 J > w; j--)//Shift, for RESULT[W] leave space result[j] = result[j-1];
      RESULT[W] = arr[i-1];
    t = Math.floor (t/i);
      } if (Validatecandidate (Result)) {Console.log (result);
    Break
}} perm ([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  Very ingenious backtracking algorithm, not recursive solve all order function seek (index, n) {var flag = false, M = n;//flag to find the location of the label, m to save the location of the search, Index[n] for the element (location code)    do {index[n]++; Sets the current position element if (index[n] = = index.length)//No location available index[n--] =-1; Resets the current position and returns to the previous position else if (! function () {for (VAR i = 0; I < n;  i++)//To determine if the current position is set to conflict with the previous position conflicts if (index[i] = = Index[n]) return true;//conflict, directly back to the loop before the element value reset returns false;
      No conflict, see whether the current position is the end of the queue, is, find an arrangement; No, move the current position}) ()//The location is not selected if (M = = N)//Current position search Complete flag = true;  else n++;
The current and previous position elements have been lined up, and the position is then moved} while (!flag && n >= 0) return flag;
  function Perm (arr) {var index = new Array (arr.length);
  for (var i = 0; i < index.length i++) Index[i] =-1;  for (i = 0; i < index.length-1. i++) Seek (index, i);
    Initialized to 1,2,3,...,-1, the last element is-1; note is small to large, if the element is not a number, can be understood as its position subscript while (Seek (index, index.length-1)) {var temp = [];
    for (i = 0; i < index.length i++) Temp.push (Arr[index[i]);
      if (validatecandidate (temp)) {Console.log (temp);
    Break

 }} perm ([1, 2, 3, 4, 5, 6, 7, 8, 9]);

/*
Full permutation (non-recursive order) algorithm
1, the establishment of the location of the array, that is, the location of the arrangement, after the success of the arrangement to convert to elements;
2, according to the following algorithm for the ranking:
Set p to be a full arrangement of 1~n (position number): p = p1,p2...pn = P1,p2...pj-1,pj,pj+1...pk-1,pk,pk+1...pn
(1) Starting from the end of the arrangement, find the first index that is smaller than the right position number J (J from the beginning), that is, j = max{i | Pi < pi+1}
(2) In the position number on the right of the PJ, find the index k of the smallest position number in the position number that is larger than PJ, that is, k = max{i | pi > PJ}
The position number on the right side of PJ is incremented from right to left, so K is the highest index in any position number larger than PJ.
(3) Exchange PJ and PK
(4) Pj+1...pk-1,pk,pk+1...pn flip to get arrange p ' = p1,p2...pj-1,pj,pn...pk+1,pk,pk-1...pj+1
(5) P ' is the next permutation of the permutation p

For example:
24310 is an arrangement of the position number 0~4, and the next step is to arrange the following:
(1) from the right to the left to find the first number of permutations than the right number 2;
(2) Find the smallest 3 of the number in the figure after the number 2;
(3) Exchanging 2 with 3 to get 34210;
(4) The original 2 (current 3) after all the numbers, that is, flip 4210, get 30124;
(5) The next permutation of 24310 is 30124.
*/

function swap (arr, I, j) {
  var t = arr[i];
  Arr[i] = arr[j];
  ARR[J] = t;

}
function sort (index) {for
  (var j = index.length-2 J >= 0 && Index[j] > index[j + 1]; j--)
    The ring begins at the end of the array of positions, finding the first left less than the right position, that is, J
  if (J < 0) return false;//completed All arrange for
  (var k = index.length-1 Index[k] < I NDEX[J]; k--)
    ; This loop starts at the end of the position array and finds the smallest of positions larger than the J position, that is, K
  Swap (index, J, K);
  for (j = j + 1, k = index.length-1 J < K; J + +, k--)
    Swap (index, J, k);/This loop flips j+1 to the end of all positions return
  TRUE;
   }
function perm (arr) {
  var index = new Array (arr.length);
  for (var i = 0; i < index.length i++)
    index[i] = i;
  do {
    var temp = [];
    for (i = 0; i < index.length i++)
      Temp.push (Arr[index[i]);
    if (validatecandidate (temp)) {
      Console.log (temp);
      break;
    }
  } while (sort (index));
Perm ([1, 2, 3, 4, 5, 6, 7, 8, 9]);

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.