What is your hint or solution suggestion?
This solution was created with the help of a programmer on Stack Overflow: https://stackoverflow.com/a/64414875/14432236
First, n is transformed into an array using the spread operator for the initial case. This leads to a recursive loop where the array is repeatedly sliced from the previous value, and new values are attached to the prefix until enough items have been selected. This is done through the ES2019 function Array.flatMap
, since the array needs to be flattened each time.
Solution 1
function combinations(k, arr, prefix=[]) {
if(prefix.length == 0) arr = [...Array(arr).keys()];
if (k == 0) return [prefix];
return arr.flatMap((v, i) =>
combinations(k-1, arr.slice(i+1), [...prefix, v])
);
}
Challenge: Combinations
Link to the challenge: