I am trying to get all of the permutations of an array, one permutation at time, using a generator.
This is the original code (which works as intended and returns an array of permutations), and below is my attempt to change 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 code, which returns nothing:
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 example, for print(permutations2([1, 2, 3], 2))
I want to get
[1, 2]
[1, 3]
[2, 1]
[2, 3]
[3, 1]
[3, 2]
However with the original code I am getting an array of the permutations:
[[1, 2],
[1, 3],
[2, 1],
[2, 3],
[3, 1],
[3, 2]]
I would be grateful to understand why my code is not working, and how to fix it. Thanks!