-
Notifications
You must be signed in to change notification settings - Fork 224
/
permutations_heap.js
43 lines (37 loc) · 1.17 KB
/
permutations_heap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Implementation of [Heap's Algorithm](https://en.wikipedia.org/wiki/Heap%27s_algorithm)
* for generating permutations.
*
* @param {Array} elements any type of data
* @returns {Array<Array>} array of permutations
*/
function permutationsHeap(elements) {
const indexes = new Array(elements.length);
const permutations = [elements.slice()];
for (let i = 0; i < elements.length; i++) {
indexes[i] = 0;
}
for (let i = 0; i < elements.length; ) {
if (indexes[i] < i) {
// At odd indexes, swap from indexes[i] instead
// of from the beginning of the array
let swapFrom = 0;
if (i % 2 !== 0) {
swapFrom = indexes[i];
}
// swap between swapFrom and i, using
// a temporary variable as storage.
const temp = elements[swapFrom];
elements[swapFrom] = elements[i];
elements[i] = temp;
permutations.push(elements.slice());
indexes[i]++;
i = 0;
} else {
indexes[i] = 0;
i++;
}
}
return permutations;
}
export default permutationsHeap;