Given an array of elements, I want a function that returns all the possible combinations, grouping adjacent elements.
Input: [1, 2, 3, 4, 5]
Expected output:
[
[1, 2, 3, 4, 5],
[[1, 2], 3, 4, 5],
[[1, 2], [3, 4], 5],
[[1, 2], 3, [4, 5]],
[1, [2, 3], 4, 5],
[1, [2, 3], [4, 5]],
[1, 2, [3, 4], 5],
[1, 2, 3, [4, 5]]
]
>Solution :
You could do this with a recursive generator. The idea is to:
- get the results for the array without the first element, and then prefix that first element to the results
- get the result for the array without the first pair, and then prefix that pair as subarray to the results
function* partition(arr) {
if (arr.length < 2) return yield arr;
for (const result of partition(arr.slice(1))) {
yield arr.slice(0, 1).concat(result);
}
for (const result of partition(arr.slice(2))) {
yield [arr.slice(0, 2)].concat(result);
}
}
const arr = [1, 2, 3, 4, 5];
console.log(Array.from(partition(arr)));