-1

Let's say input array is

      [a0,a1,a2],[b0,b1], [c0,c1]
]

And expected output something like this

a0 b0 c0,
a0 b0 c1,
a0 b1 c0,
a0 b1 c1
a1 b0 c0,
a1 b0 c1,
a1 b1 c0,
a1 b1 c1
.......
a2 b1 c1

After writing out longhand these combinations I can sense patterns, like there are some fixed positions and then index moves from left to right, then left again and everything but cannot wrap my head around the multidimensionallity and how to implement? Loop inside loop inside loop, recursion or what? I am looking for general directions.

Any suggestions and tips would be much appreciated

Red Hood
  • 3
  • 3

1 Answers1

0

This has a lot of recursive characteristics, but it's slightly more complicated than just permutations:

const foo = [
  ['a0', 'a1', 'a2'],
  ['b0', 'b1'],
  ['c0', 'c1'],
];

function getCombinations(prefixArr, arr) {
  if (!arr[0]) return prefixArr;

  return arr[0].map((element) => getCombinations(
    [...prefixArr, element],
    [...arr].splice(1),
  ));
}

function getCombinationsWrapper(arr) {
  let ans = getCombinations([], arr);
  for (let i = 0; i < arr.length - 1; i++) {
    ans = ans.flat();
  }
  return ans;
}

console.log(getCombinationsWrapper(foo));
GalAbra
  • 5,048
  • 4
  • 23
  • 42