javaalgorithmrecursionpermutationheaps-algorithm

Returning an array in Heap's recursive algorithm


I've implemented the Heap's algorithm for finding all permutations of the elements of array A:

//A = {1, 2, 3, 4}; B = perms(A) ; num_row(B) = (4!+1) and B[0][0] = 4!;
//This is B.R. Heap's algorithm
public static void perms(int [] A, int [][]B, int n)
{
   if (n == 1)
   {
       int k = B[0][0];
       for (int i = 0; i < A.length; i++)
       {
           B[k + 1][i] = A[i];
       }
       B[0][0]++;
   }
   else
   {
       for (int i = 0; i < n - 1 ;i++)
       {
           perms(A, B, n-1);
           if (n % 2 == 0)
           {
               swap(A, i, n - 1);
           }
           else
           {
               swap(A, 0, n - 1);
           }
       }
       perms(A, B, n - 1); 
   }
}
public static void swap(int[] A, int i, int j)
{
    int temp = A[i];
    A[i] = A[j];
    A[j] = temp;
}

I'm new to Java. The problem is I want to have B as the output (return) of the function perms(A) , but in this implementation, I have to initialize a int[n! + 1][A.length] B array before calling the function. How can I do it?
Is there anything like private variable or anything in java to help a recursive function to remember a variable from a former call?

Thanks


Solution

  • You can create an "entering" method to recursion like this:

    public static int[][] perms(int[] a){
        int[][] perms = new int[factorial(a.length)+1][a.length];
        perms(a,perms,a.length);
        return perms;
    }
    

    Method factorial is well know method and can be found on Google for example
    Wondering if n parameter is neccessary

    EDIT

    it is not neccessary (above corrected)

    EDIT

    By my test the k variable is just incrementing, so I would use static variable like this:

    private static int counter = 0;
    // your code here, following is a part of your perms method
    if (n == 1)
    {
        for (int i = 0; i < A.length; i++)
        {
            B[counter][i] = A[i];
        }
        counter++;
    }
    //and my code corrected too:
    public static int[][] perms(int[] a){
        int[][] perms = new int[factorial(a.length)][a.length]; //+1 is not necessary
        counter=0; //necessary to call it again
        perms(a,perms,a.length);
        return perms;
    }