Search code examples
javascriptarraysrecursionheaps-algorithm

Heap's algorithm to return array instead of printing


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]];
    }
  }
}

Solution

  • Just make it return that result as an array, and collect return values from your recursive calls in the loop:

    function heaps(arr, n = arr.length) {
      if (n <= 1) return [arr.slice()];
      let result = [];
      for (let i = 0; i <= n - 1; i++) {
        result.push(...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]];
      }
      return result;
    }
    

    Alternatively, make an inner helper function that does push to an outer array

    function heaps(arr) {
      let result = [];
      function helper(n) {
        if (n <= 1)
          result.push(arr.slice());
        else
          for (let i = 0; i <= n - 1; i++) {
            heaps(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]];
          }
      }
      helper(arr.length);
      return result;
    }
    

    If you insist on not using an "outer" array, make the result array and the input arr explicit parameters of the helper function.