I’m having trouble figuring out how to generate a combination of values.
Given:
JavaScript
x
2
1
const items = ['a', 'b', 'c', 'd', 'e'];
2
should generate:
JavaScript
1
14
14
1
[
2
['a', 'b', 'c'],
3
['a', 'b', 'd'],
4
['a', 'b', 'e'],
5
['a', 'c', 'd'],
6
['a', 'c', 'e'],
7
['a', 'd', 'e'],
8
9
['b', 'c', 'd'],
10
['b', 'c', 'e'],
11
12
['c', 'd', 'e']
13
]
14
It generates a unique combination for all the items in the array.
Basically, the length of the array for each item is Math.round(items.length / 2)
.
Any help would be greatly appreciated.
Advertisement
Answer
You could take a straight forward approach and iterate the array and get the parts of the rest array by respecting the wanted length.
JavaScript
1
8
1
function perm(array, length) {
2
return array.flatMap((v, i) => length > 1
3
? perm(array.slice(i + 1), length - 1).map(w => [v, w])
4
: [[v]]
5
);
6
}
7
8
perm(['a', 'b', 'c', 'd', 'e'], 3).forEach(a => console.log(a));
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }