0

I've seen several similar questions about how to generate all possible combinations of elements in an array. But I'm having a very hard time figuring out how to write an algorithm that will output all pairs and sets at any unique order. Any suggestions would be super appreciated!

Starting with the following array (with N elements):

let array = ["a", "b", "c", "d", "e];

And getting the following result:

var result = [
   [a, b]
   [a, b, c]
   [a, c,]
   [b, a]
   [a, b, c ,d]
   [d, c, b, a]
   ...
];

tried using power set but it was missing combinations that are in different order

function powerSet( list ){
    var set = [],
        listSize = list.length,
        combinationsCount = (1 << listSize),
        combination;

    for (var i = 1; i < combinationsCount ; i++ ){
        var combination = [];
        for (var j=0;j<listSize;j++){
            if ((i & (1 << j))){
                combination.push(list[j]);
            }
        }
        set.push(combination);
    }
    return set;
}

var combinations = powerSet(["a", "b", "c", "d", "e"]);
console.log(combinations)

the result have missing combinations like ab, ba ...

Marr
  • 555
  • 1
  • 6
  • 11
  • According to what you said *"i wanted to include ["c","d"] and ["d","c"] as i consider each unique by order* - for 3 items (`a, b, c)` the number of combinations isn't `1<<3` (`8`). I can make `a`, `a, b` `a, c` `a, b, c` `a, c, b` just starting with `a`, similar for others – T J Aug 14 '21 at 08:08

1 Answers1

0

Since your powerSet is working as expected, you can just flatMap some routine which gives you all possible orders:

const combinations = powerSet(["a", "b", "c", "d", "e"]).flatMap(permutator)

For the implementation of permutator see this answer.

Josef Wittmann
  • 1,259
  • 9
  • 16