Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate an array with all possible combinations grouping adjacent elements?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    [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)));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading