fix(permutations-heap): do the swaps on a copy of the input
Heap's Algorithm generates each permutation by swapping two elements of a working array in place, and that working array was the argument itself, so permutationsHeap([1, 2, 3]) left the caller holding [3, 2, 1]. Two calls on one array returned different lists, and a frozen array threw. Copy the input up front and swap on the copy, as shuffle and numericSort already do. The returned permutations are unchanged.
This commit is contained in:
1 parent
cd7bef4165
commit
5894b8b560
3 files changed
+35
-8
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"simple-statistics": patch
|
||||
---
|
||||
|
||||
Fix `permutationsHeap` permuting the caller's array. Heap's Algorithm works by swapping elements in place, and the implementation ran those swaps directly on the argument, so `permutationsHeap([1, 2, 3])` left the caller holding `[3, 2, 1]`, the last permutation generated. Calling it twice on the same array returned two different lists, and a frozen input threw `TypeError: Cannot assign to read only property '0'`. The swaps now run on a copy, matching the defensive copying already used in `shuffle`. The returned permutations are unchanged.
|
||||
Reference in new issue
Block a user