Home >Web Front-end >JS Tutorial >Array full arrangement output algorithm implemented by JS_javascript skills

Array full arrangement output algorithm implemented by JS_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:08:361402browse

The example in this article describes the full array output algorithm implemented by JS. Share it with everyone for your reference. The specific analysis is as follows:

This js code fully arranges and outputs the array, improving some old codes
Randomly selecting m (m ≤ n) elements from n different elements and arranging them in a certain order is called an arrangement of m elements from n different elements. When m=n, all permutations are called full permutations.

function permute(input) {
  var permArr = [],
  usedChars = [];
  function main(input){
    var i, ch;
    for (i = 0; i < input.length; i++) {
      ch = input.splice(i, 1)[0];
      usedChars.push(ch);
      if (input.length == 0) {
        permArr.push(usedChars.slice());
      }
      main(input);
      input.splice(i, 0, ch);
      usedChars.pop();
    }
    return permArr
  }
  return main(input);
};
console.log(permute([5, 3, 7, 1]));

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
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