【发布时间】:2020-04-06 23:50:12
【问题描述】:
这里的第一个问题(我认为)。请让我知道是否需要其他信息以便你们帮助我。
所以我正在尝试在 javascript 中实现一个使用递归函数的算法。
该函数是从Implementing Heap Algorithm of Permutation in JavaScript复制而来的,如下所示:
let swap = function(array, index1, index2) {
let temp = array[index1]
array[index1] = array[index2]
array[index2] = temp
return array
}
let permutationHeap = (array, result, n) => {
n = n || array.length // set n default to array.length
if (n === 1) {
result(array)
} else {
for (let i = 1; i <= n; i++) {
permutationHeap(array, result, n - 1)
if (n % 2) {
swap(array, 0, n - 1) // when length is odd so n % 2 is 1, select the first number, then the second number, then the third number. . . to be swapped with the last number
} else {
swap(array, i - 1, n - 1) // when length is even so n % 2 is 0, always select the first number with the last number
}
}
}
}
let output = function(input) {
console.log(output)
}
permutationHeap([1,2,3,4,5], output)
输出函数(回调?)中的 console.log 给了我正确的输出。如果我将 console.log 移到 permutationHeap-function 中的 if 语句下方,我也会得到正确的输出(虽然在这种情况下是 console.log(array))。
我想要做的是将每个输出存储为一个数组,存储在一个我以后可以使用的数组中。我猜我在这里遇到了 Javascript 101。处理异步思维。但是我一生都无法弄清楚如何获得该数组!
- 如果我在 permutationHeap 函数之外声明一个空数组并且 .push(array) 它只存储 [1,2,3,4,5]。如果我做同样的事情,同样的交易 输出函数内部的东西。
- 我还尝试将一个空数组传递给 permutationHeap-function 并以这种方式推送。还是没有运气。
有人愿意为一个可能是超级菜鸟的问题提供一些启发吗? :) 非常感谢!
【问题讨论】:
标签: javascript arrays recursion