Home>Article>Web Front-end> JS full permutation and combination algorithm implementation method
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));
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!