1 | /**
|
2 | * Implementation of Combinations
|
3 | * Combinations are unique subsets of a collection - in this case, k x from a collection at a time.
|
4 | * https://en.wikipedia.org/wiki/Combination
|
5 | * @param {Array} x any type of data
|
6 | * @param {int} k the number of objects in each group (without replacement)
|
7 | * @returns {Array<Array>} array of permutations
|
8 | * @example
|
9 | * combinations([1, 2, 3], 2); // => [[1,2], [1,3], [2,3]]
|
10 | */
|
11 |
|
12 | function combinations(x, k) {
|
13 | let i;
|
14 | let subI;
|
15 | const combinationList = [];
|
16 | let subsetCombinations;
|
17 | let next;
|
18 |
|
19 | for (i = 0; i < x.length; i++) {
|
20 | if (k === 1) {
|
21 | combinationList.push([x[i]]);
|
22 | } else {
|
23 | subsetCombinations = combinations(x.slice(i + 1, x.length), k - 1);
|
24 | for (subI = 0; subI < subsetCombinations.length; subI++) {
|
25 | next = subsetCombinations[subI];
|
26 | next.unshift(x[i]);
|
27 | combinationList.push(next);
|
28 | }
|
29 | }
|
30 | }
|
31 | return combinationList;
|
32 | }
|
33 |
|
34 | export default combinations;
|