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.
35 lines
1.1 KiB
JavaScript
35 lines
1.1 KiB
JavaScript
import assert from "node:assert/strict";
|
|
import { describe, it } from "node:test";
|
|
import * as ss from "../index.js";
|
|
|
|
describe("permutationsHeap", function () {
|
|
it("generates 1 permutation", function () {
|
|
assert.deepEqual(ss.permutationsHeap([1]), [[1]]);
|
|
});
|
|
it("generates 1, 2, 3 permutations", function () {
|
|
assert.deepEqual(ss.permutationsHeap([1, 2, 3]), [
|
|
[1, 2, 3],
|
|
[2, 1, 3],
|
|
[3, 1, 2],
|
|
[1, 3, 2],
|
|
[2, 3, 1],
|
|
[3, 2, 1]
|
|
]);
|
|
});
|
|
it("does not modify the caller's array", function () {
|
|
const x = [1, 2, 3];
|
|
ss.permutationsHeap(x);
|
|
assert.deepEqual(x, [1, 2, 3]);
|
|
});
|
|
it("accepts a frozen array", function () {
|
|
assert.deepEqual(ss.permutationsHeap(Object.freeze([1, 2])), [
|
|
[1, 2],
|
|
[2, 1]
|
|
]);
|
|
});
|
|
it("returns the same permutations when called twice on one array", function () {
|
|
const x = [1, 2, 3];
|
|
assert.deepEqual(ss.permutationsHeap(x), ss.permutationsHeap(x));
|
|
});
|
|
});
|