Home > Web Front-end > JS Tutorial > body text

JS full permutation and combination algorithm implementation method

小云云
Release: 2018-01-27 11:20:00
Original
6417 people have browsed it

Full permutation and combination algorithm, for example, if a, b, c, d are fully permuted and combined, the combination result is: a, b, ab, c, ac, bc, abc, d, ad, bd, abd, cd, acd, bcd, abcd. Implementation idea: take out an element from the data source, combine it with the existing combined data in turn, and loop the above operations until there is no data in the data source.

This article mainly introduces the full permutation and combination algorithm implemented by JS. It briefly describes the principle of the full permutation and combination algorithm and gives the specific implementation skills of the full permutation and combination algorithm in the form of examples. Friends who need it can For reference, I hope it can help everyone.

Example:

Data sources a, b, c

1. Take out a, the combined data group is empty, and insert the data source a element into Combine the data group, at this time group=[a]
2. Take out b, take out a from the combined data group, combine a and b, get ab, insert the data source b element and ab into the combined data group, at this time group =[a,b,ab]
3. Take out c, combine the data group, take out a, b, ab, combine with c respectively, get ac, bc, abc respectively, put the data source c element, ac, bc , abc inserts the combined data group, at this time group=[a,b,ab,c,ac,bc,abc]

js code:


var data = ['a','b','c','d'];
function getGroup(data, index = 0, group = []) {
  var need_apply = new Array();
  need_apply.push(data[index]);
  for(var i = 0; i < group.length; i++) {
    need_apply.push(group[i] + data[index]);
  }
  group.push.apply(group, need_apply);
  if(index + 1 >= data.length) return group;
  else return getGroup(data, index + 1, group);
}
console.log(getGroup(data));
Copy after login

Running output result:

Related recommendations:

Detailed explanation of several non-recursive full permutation algorithm code examples in JavaScript

php Full Permutation Recursive Algorithm Sample Code

JavaScript Interesting Question: Full Permutation Removal

The above is the detailed content of JS full permutation and combination algorithm implementation method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template