-4

If I have a given array of digits, eg:

[1, 2, 7, 1, 9]

How can I recursively create an array of all possible combinations of these digits, eg:

[12719, 12791, 12971, 12179, etc...]

I would like to accomplish this with something like:

const producePossibleNumbers = (digits) => {

    return digits.map((d, index) => {

        const remainingDigits = digits.filter((x, i) => i !== index)
        if (remainingDigits.length === 1) {
            return d + remainingDigits[0]
        } else {
            producePossibleNumbers(remainingDigits)
        }

    })    

}

Obviously this is complete / non-functional code... Need a jump start.

j_d
  • 2,818
  • 9
  • 50
  • 91
  • 2
    here's a jump start... a search for array permutations with tons of results https://stackoverflow.com/search?q=%5Bjavascript%5D+array+permutations – charlietfl Aug 05 '18 at 17:39
  • Or [this](https://rosettacode.org/wiki/Combinations#JavaScript) or [this](https://codereview.stackexchange.com/questions/7001/generating-all-combinations-of-an-array) or.... – Jared Smith Aug 05 '18 at 17:46
  • Possible duplicate of [Permutations in JavaScript?](https://stackoverflow.com/questions/9960908/permutations-in-javascript) – j_d Aug 07 '18 at 09:16

1 Answers1

2

This is a perfect usecase for recursive generators:

 function* combinations(arr, prepend = []) {
   if(arr.length === 1) {
     yield prepend.concat(arr[0]);
     return;
   }
   for(const [index, el] of arr.entries()) {
     yield* combinations(arr.filter((_, i) => i !== index), prepend.concat([el]));
   }
 }

Usable as:

 [...combinations([1, 2, 7, 1, 9])]
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151