JavaScript to solve the third-order magic square

Source: Internet
Author: User
Tags reset sort

JavaScript to solve the third-order magic square

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.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 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 first element, reduce array size var chi Ldpermutation = Getpermutation (Arrclone);//recursive for (var j = 0; J < Childpermutation.length; + +) {childpermutation[j].u Nshift (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 & Lt 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, I Sforwardslash) {return isforwardslash? Candidate[2] + candidate[4] + candidate[6]: candidate[0] + candidate[4] + Candid ATE[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 ');  //modulus (non-recursive) All-ranked algorithm  /* Specific examples of algorithms: * 4 Elements ["A", "B", "C", "D"] of the full arrangement, the total circulation 4!=24 times, can be from any >=0 integer index start loop, each cumulative 1, until the end of the cycle index+23; * Assuming 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, the 2nd element is inserted in the 1th position (that is, subscript 1), ["A", "B"]; * The 3rd iteration, 6/3, quotient =2, remainder = 0, so the 3rd element inserts No. 0 position (that is subscript 0), get ["C", "A", "B"]; * 4th iteration, 2/4, quotient =0, remainder = 2, So the 4th element inserts the 2nd position (that is, subscript 2), get ["C", "a", "D", "B"]; *   function perm (arr) {var result = new Array (arr.length); var fac = 1; for (var i = 2; I <= arr.length ; i++)///According to the length of the array to calculate the number of permutations FAC *= i; for (var index = 0; index < FAC; index++) {//each index corresponds to an array of var t = index; for (i = 1; I <= arr.length; i++) {//OK 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) {console.log (result); Perm ([1, 2, 3, 4, 5, 6, 7, 8, 9]); Very ingenious backtracking algorithm, non-recursive solution for all permutation   function seek (index, n) {var flag = false, M = n;//flag to find the location of the label, M save the location of the search, Index[n] for the element (location (code) do {index[n]++;//Set the current position element if (index[n] = = index.length)//No position available index[n--] =-1;//reset current position, back to previous position else if (!) ( function () {for (var i = 0; i < n; i++)//Determine if the settings for the current position are conflicting with the previous position conflict if (index[i] = = Index[n]) Return true;//conflict, go straight back to the loop before you reset the meta The element value return 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; = 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 = []; 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.

*/

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The 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 loop starts at the end of the location array, finding the first left less than the right position, i.e. J if (J < 0) return false; All arrangements have been completed for (var k = index.length-1 Index[k] < index[j]; k--); This loop starts at the end of the position array and finds the smallest of the 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 all positions at the end of J+1 to 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 is the entire contents 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.