I am on a mission to generate permutations of an array, one permutation at a time, using a generator.
Here is the existing code (which successfully produces an array of permutations), followed by my attempt to modify it:
function permutations(iList, maxLength) {
const cur = Array(maxLength)
const results = []
function rec(list, depth = 0) {
if (depth === maxLength) {
return results.push(cur.slice(0))
}
for (let i = 0; i < list.length; ++i) {
cur[depth] = list.splice(i, 1)[0]
rec(list, depth + 1)
list.splice(i, 0, cur[depth])
}
}
rec(iList)
return results
}
My updated code, which unfortunately does not produce any output:
function* permutations2(iList, maxLength) {
const cur = Array(maxLength)
function* rec(list, depth = 0) {
if (depth === maxLength) {
yield cur.slice(0)
}
for (let i = 0; i < list.length; ++i) {
cur[depth] = list.splice(i, 1)[0]
rec(list, depth + 1)
list.splice(i, 0, cur[depth])
}
}
yield rec(iList)
}
For instance, with
print(permutations2([1, 2, 3], 2))
, I aim to achieve:
[1, 2]
[1, 3]
[2, 1]
[2, 3]
[3, 1]
[3, 2]
However, with the original code, I receive an array of permutations within arrays:
[[1, 2],
[1, 3],
[2, 1],
[2, 3],
[3, 1],
[3, 2]]
I would appreciate insights into why my code is failing to work and how I can rectify it. Thank you!