I am trying to get this heaps algorithm to return an array of permutations instead of printing as below. I know it could be done by declaring an array outside of the function and pushing to it but, I want to avoid that approach. How can I make this return the array of permutations without using an outside array?
function heaps(arr, n) {
if (n === undefined) n = arr.length;
if (n <= 1) console.log(arr);
else {
for (let i = 0; i <= n - 1; i++)
{
heaps(arr, n-1);
if
(n % 2 === 0) [arr[n-1], arr[i]] = [arr[i], arr[n-1]];
else
[arr[n-1], arr[0]] = [arr[0], arr[n-1]];
}
}
}
Just make it
return
that result as an array, and collect return values from your recursive calls in the loop:Alternatively, make an inner helper function that does push to an outer array
If you insist on not using an "outer" array, make the
result
array and the inputarr
explicit parameters of the helper function.