So, I’ve tried implementing Heap’s Algorithm for the Day 4 solution of the Advent of Code, but it never seems to work correctly. I follow the algorithm to the T, and yet there’s always some sort of issue.

I looked through these links:

And have tried variations on them. Still nothing

Here’s the code that I have written. It seems to work fine up until you go beyond a string with a length of 4. After that, it starts to repeat the same combinations, and it skips other combinations that are possible

```
function heapPermutation(word) {
const wordArr = word.split('');
const perms = [];
function swap(i, j) {
const temp = wordArr[i];
wordArr[i] = wordArr[j];
wordArr[j] = temp;
}
function generate(n) {
if (n === 1) {
perms.push(wordArr.join(''));
}
else {
for (let i = 0; i < n-1; i++) {
generate(n-1);
swap(i%2 ? 0 : i, n-1);
}
generate(n-1);
}
}
generate(wordArr.length);
return perms;
}
```