简体   繁体   English

Javascript 堆的算法(非递归)

[英]Javascript Heap's algorithm (non-recursive)

I have implemented Heap's non-recursive algorithm in JavaScript.我已经在 J​​avaScript 中实现了 Heap 的非递归算法。 When checking permutations with console.log(arr) everything works as expected.当使用console.log(arr)检查排列时,一切都按预期工作。 But when I try to push each permutation to a result array, then everything breaks up.但是,当我尝试将每个排列推送到结果数组时,一切都会破裂。 It just returns result filled with last iteration permutation.它只返回填充了上次迭代排列的结果。

 function generate(n, arr) { function swap(item1, item2){ console.log(item1, item2); let tmp = arr[item1]; arr[item1] = arr[item2]; arr[item2] = tmp; } var c = []; var allPermutations = []; for (let i = 0; i < n; i++) { c[i] = 0; } console.log(arr); allPermutations.push(arr); for (let i = 1; i < n; i) { if (c[i] < i) { if (i % 2 == 0) { swap(0, i); } else { swap(c[i], i); } console.log(arr); allPermutations.push(arr); c[i] += 1; i = 1; } else { c[i] = 0; i += 1; } } return allPermutations; } console.log('result', generate(3, ["a", "a", "b"]));

The problem is that arrays are just references so when you push in the array you are just pushing a reference to it.问题在于数组只是引用,因此当您推入数组时,您只是推入了对它的引用。 So, on the next iteration you update the array and when you look at the final output, all the indexes will be the same since it is the same array.因此,在下一次迭代中更新数组,当您查看最终输出时,所有索引都将相同,因为它是相同的数组。

So what can you do?所以,你可以做什么? clone it.克隆它。

allPermutations.push(arr.slice(0));

Yep - its a reference problem.是的 - 它是一个参考问题。 Alternative to epascarello's answer:替代 epascarello 的回答:

allPermutations.push([...arr]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM