Home Web Front-end JS Tutorial JavaScript solves the third-order magic square (nine-square grid)_javascript skills

JavaScript solves the third-order magic square (nine-square grid)_javascript skills

May 16, 2016 pm 04:02 PM
javascript Jiugongge

Puzzle: Third-order magic square. Try to fill in the 9 different integers from 1 to 9 into a 3×3 table so that the sum of the numbers in each row, column and diagonal is the same.

Strategy: Exhaustive search. List all integer padding scenarios, then filter.

The highlight is the design of the recursive function getPermutation. At the end of the article, several non-recursive algorithms are given

// 递归算法,很巧妙,但太费资源
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 &#63; 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');
}

//求模(非递归)全排列算法

/*
算法的具体示例:
*求4个元素["a", "b", "c", "d"]的全排列, 共循环4!=24次,可从任意>=0的整数index开始循环,每次累加1,直到循环完index+23后结束;
*假设index=13(或13+24,13+224,13+3*24…),因为共4个元素,故迭代4次,则得到的这一个排列的过程为:
*第1次迭代,13/1,商=13,余数=0,故第1个元素插入第0个位置(即下标为0),得["a"];
*第2次迭代,13/2, 商=6,余数=1,故第2个元素插入第1个位置(即下标为1),得["a", "b"];
*第3次迭代,6/3, 商=2,余数=0,故第3个元素插入第0个位置(即下标为0),得["c", "a", "b"];
*第4次迭代,2/4,商=0,余数=2, 故第4个元素插入第2个位置(即下标为2),得["c", "a", "d", "b"];
*/

function perm(arr) {
  var result = new Array(arr.length);
  var fac = 1;
  for (var i = 2; i <= arr.length; i++)  //根据数组长度计算出排列个数
    fac *= i;
  for (var index = 0; index < fac; index++) { //每一个index对应一个排列
    var t = index;
    for (i = 1; i <= arr.length; i++) {   //确定每个数的位置
      var w = t % i;
      for (var j = i - 1; j > w; j--)   //移位,为result[w]留出空间
        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]);
//很巧妙的回溯算法,非递归解决全排列

function seek(index, n) {
  var flag = false, m = n; //flag为找到位置排列的标志,m保存正在搜索哪个位置,index[n]为元素(位置编码)
  do {
    index[n]++;    //设置当前位置元素
    if (index[n] == index.length) //已无位置可用
      index[n--] = -1; //重置当前位置,回退到上一个位置
    else if (!(function () {
        for (var i = 0; i < n; i++)  //判断当前位置的设置是否与前面位置冲突
          if (index[i] == index[n]) return true;//冲突,直接回到循环前面重新设置元素值
        return false;  //不冲突,看当前位置是否是队列尾,是,找到一个排列;否,当前位置后移
      })()) //该位置未被选择
      if (m == n) //当前位置搜索完成
        flag = true;
      else
        n++;  //当前及以前的位置元素已经排好,位置后移
  } 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);  //初始化为1,2,3,...,-1 ,最后一位元素为-1;注意是从小到大的,若元素不为数字,可以理解为其位置下标
  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]);

Copy after login

/*
Full permutation (non-recursive ordering) algorithm
1. Create a position array, that is, arrange the positions. After the arrangement is successful, it is converted into an arrangement of elements;
2. Find the complete arrangement according to the following algorithm:
Suppose P is a complete arrangement of 1 to n (position numbers): 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 j that is smaller than the right position number (j is calculated from the beginning), that is, j = max{i | pi < pi 1}
(2) Among the position numbers to the right of pj, find the index k of the smallest position number among all position numbers larger than pj, that is, k = max{i | pi > pj}
The position numbers to the right of pj increase from right to left, so k is the largest index among all position numbers greater than pj
(3)Exchange pj and pk
(4) Then flip pj 1...pk-1,pk,pk 1...pn to get the arrangement p' = p1,p2...pj-1,pj,pn...pk 1,pk,pk -1...pj 1
(5) p' is the next permutation of permutation p

For example:
24310 is a permutation of position numbers 0 to 4. The steps to find its next permutation are as follows:
(1) Find the first number 2 in the arrangement that is smaller than the number on the right from right to left;
(2) Find the smallest number 3 that is greater than 2 among the numbers after the number;
(3) Swap 2 and 3 to get 34210;
(4) Flip all the numbers after the original 2 (current 3), that is, flip 4210 to get 30124;
(5) Find the next permutation of 24310 as 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--)
    ; //本循环从位置数组的末尾开始,找到第一个左边小于右边的位置,即j
  if (j < 0) return false; //已完成全部排列
  for (var k = index.length - 1; index[k] < index[j]; k--)
    ; //本循环从位置数组的末尾开始,找到比j位置大的位置中最小的,即k
  swap(index, j, k);
  for (j = j + 1, k = index.length - 1; j < k; j++, k--)
    swap(index, j, k); //本循环翻转j+1到末尾的所有位置
  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]);
Copy after login

The above is the entire content of this article, I hope you all like it.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to automatically generate a nine-square grid cutout on Weibo_How to automatically generate a nine-square grid cutout on Weibo How to automatically generate a nine-square grid cutout on Weibo_How to automatically generate a nine-square grid cutout on Weibo Mar 30, 2024 pm 05:51 PM

1. First open Weibo and select [Write Weibo] in the upper right corner. 2. Then press and hold the picture symbol as shown in the picture. Remember to press and hold. 3. Then automatically enter the photo album and select the picture you want to cut. 4. Then click Move and Zoom to change the size of the cut, and click Publish.

See all articles