Search code examples
javaarrayspermutation

Recursive method to permute characters in array Java


I am trying to solve my homework. My task is to create an recursive method called void permute(char[] a, int lengthOfa) to permute the characters a,b,c,d like this:

  • a b c d
  • b a c d
  • a c b d
  • c a b d
  • c b a d
  • b c a d

This is the code I have come up with so far:

public class Main {
    public static void main(String[] args) {

        char[] charArray = {'a', 'b', 'c', 'd'};


        permute(charArray, 3);

    }

    public static void permute(char[] a, int lengthOfa) {

        System.out.println(a);

        if (lengthOfa <= 1) {
            return;
        }


        char temp = a[lengthOfa];

        a[1] = a[2];
        a[2] = temp;

        permute(a, lengthOfa - 1);


    }

}

How am I able to solve the task?


Solution

  • Thanks to the help of the comment of @Johnny Mopp I found a solution by myself:

    public class Main2 {
    
    public static void main(String[] args) {
    
        char[] charArray = {'a', 'b', 'c', 'd'};
    
    
        permute(charArray, charArray.length);
    
    }
    
    public static void permute(char[] a, int lengthOfa) {
    
        if (lengthOfa == 1) {
            printArray(a, 4);
        }
    
        for (int i = 0; i < lengthOfa; i++) {
    
            permute(a, lengthOfa - 1);
    
            if (lengthOfa % 2 == 1) {
                char temp = a[0];
                a[0] = a[lengthOfa - 1];
                a[lengthOfa - 1] = temp;
    
            } else {
                char temp = a[i];
                a[i] = a[lengthOfa - 1];
                a[lengthOfa - 1] = temp;
    
    
            }
    
        }
    
    }
    
    public static void printArray(char[] a, int n) {
        for (int i = 0; i < n; i++)
            System.out.print(a[i] + " ");
        System.out.println();
    }
    

    }