0

Hi can anyone please help me. I want to be able to generate all possible combinations of the array but only certain elements will be changing given two possible numbers to choose from. Their position is important too.

For example: let arr = [1,2,3, (4 or 5), (6 or 7), (8 or 9)]

I want to generate
1,2,3,4,6,8
1,2,3,4,6,9
1,2,3,4,7,8
.
.
.
.
This goes on until 1,2,3,5,7,9

I know it is very similar to binary numbers, I just don't know how to go about it and also the array may change in size so it can lead to a lot of options and possible outcomes.

Please. Someone help.

Edit: clarified the combinations I want to generate

anlo
  • 43
  • 3
  • but there should be 8 (sorry, didn't read it right) possibilities, not 3 ... right? you'll want some loops maybe 4 ... but it could be done with less – Bravo Apr 23 '22 at 23:13
  • oh sorry, I forgot to add that it goes on. Wouldn't there be only 8 possibilities because of 2^3? The first 3 elements remain constant. – anlo Apr 23 '22 at 23:16
  • yeah, 8 - re-read the question :p – Bravo Apr 23 '22 at 23:18
  • 1
    so, something like `const result = Array.from({length:8}, (_, n) => [1,2,3,[4,5][+!!(n&4)],[6,7][+!!(n&2)],[8,9][+!!(n&1)]])` – Bravo Apr 23 '22 at 23:22
  • oh wow! this is exactly what I wanted. Thank you so much!!! I'll look into it more as I don't really understand what "+!!" means – anlo Apr 23 '22 at 23:25
  • 1
    the `!!` converts the result of the & operator to false if 0, and to true if not 0, then the `+` converts false to 0 and true to 1 to get an index of 0 or 1 - there is other ways to do it though - `const result = Array.from({length:8}, (_, n) => [1,2,3,[4,2,1][4,5][(n&4)>>2],[6,7][(n&2)>>1],[8,9][(n&1)]])` for example – Bravo Apr 23 '22 at 23:28
  • 1
    The general idea you're looking for is the "cartesian product" of multiple arrays; see the answers to the linked question. If you use the code there here it gives you [this](https://tsplay.dev/WoGzlW). – jcalz Apr 23 '22 at 23:30
  • Thank you so much to both of you!! I was really having a hard time and both of you are so helpful! – anlo Apr 23 '22 at 23:37

0 Answers0