I've had a look around this site but I have been unable to find an answer that includes duplicate elements. For example, given the array:
[1,2,3,4]
With a length of 3, A function should generate a list of every single possible combination with those numbers, using each one more than once:
[
[1,1,1],
[1,1,2],
[1,1,3],
...
[4,4,2],
[4,4,3],
[4,4,4]
]
I just haven't been able to get my head around the algorithm that I should use. I don't expect a code answer, but a push in the right direction would be appreciated.
I've tried using reduce like so:
const arr = [1, 2, 3, 4]
const len = 3
arr.reduce((acc, n) => {
for (let i = 0; i < len; i++) {
acc.push(/* ???? */)
}
return acc
}, [])
but I really don't know how to continue.
As a side note, ideally, I would like to do this as efficiently as possible.