5
\$\begingroup\$

Here are the items:


    var item = ['a', 'b', 'c', 'd'];

Desired output:


    [
        [ ['a'],['b'],['c'],['d'] ],
        [ ['a'],['b','c'],['d'] ],
        [ ['a'],['b'],['c','d'] ],
        [ ['a'],['b','c','d'] ],
        [ ['a'],['c'],['b','d'] ],....
    ]

The code:

function getCombinations(items) {
   var res = [];
   for (var i = 0; i < items.length; i++) {
      for (var j = i + 1; j <= items.length; j++) {
         var temp = items.slice(i, j);
         var remained = items.slice(0, i).concat(items.slice(j, items.length));
         if (remained.length > 0) {
            var combinations = getCombinations(remained);
            combinations.forEach(combination => {
               res.push([temp].concat(combination));
            });
         } else {
            res.push([temp]);
         }
      }
    }
   return res;
}

var item = ['a', 'b', 'c', 'd'];

console.log(getCombinations(item));

\$\endgroup\$
2
  • \$\begingroup\$ You output for ['a', 'b', 'c', 'd'] doesn't contain [['a', 'c'], ['b', 'd']] which may be incorrect. Also, your output contain duplicate [['a'], ['b'], ['c'], ['d']], [['a'], ['b'], ['d'], ['c']]. \$\endgroup\$
    – tsh
    Commented Feb 10, 2021 at 6:25
  • \$\begingroup\$ The number of partitions is known as Bell number, which may be quite large when there are more items in the input. As a result, any valid solution won't be much fast due to the fact of output size. \$\endgroup\$
    – tsh
    Commented Feb 10, 2021 at 6:46

1 Answer 1

1
\$\begingroup\$

I see the tag added to this post. Did you intend to have answers address performance in terms of time, space or other aspects?

If you are looking to optimize performance in terms of time then I must restrain myself from suggesting changing the outer for loop to a for of loop. However I do see there is a forEach loop inside the nested for loop. If you really want to optimize for performance, then consider using a for loop instead of that .forEach method. Also consider whether the same result can be achieved by iterating backwards through the loops - this would allow for fewer operations1.

Given that an arrow function is used in the .forEach() callback, other features can be used - e.g. const and let instead of var, spread syntax instead of calling .concat(), etc.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.