Search code examples
javarecursionbacktracking

Permutation of a String of ints


I'm doing a Java assignment this week where we're expected to use a set to backtrack through a String recursively and find all permutations of said String, culminating in an int of maximum size from the numbers contained within the string. This part alone is fine. The issue is that we are expected to set the length of this integer, shown here in int z.

For example, the expected output of method maxDigit("12345",3) would be: 543. Could you please point out where I need to be looking to improve my code?

Cheers.

    /**
 * Returns the maximum possible integer given the string str containing digits, using
 * maximum of n digits. Each digit in str can only be used once.
 **/
static int maxDigit(String str, int z) {
    Set<Integer> result = new TreeSet<>();

    if(str.length() == 0 || z == 0)
        return -1;

    permute("",str,result,z);

    int answer = 0;
    for(int a : result) {
        if(a > answer)
            answer = a;
    }
    return answer;
}

/**
 * Creates a set of permutations in result based on string str with max n digits.
 **/
private static void permute(String acc, String str,Set<Integer> result,int z) {
    int n = str.length();
    if (n == 0)
        result.add(Integer.parseInt(acc));
    else {
        if(!(z < str.length())) {
            for (int i = 0; i < n; i++)
                permute(acc + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n), result, z);
        } else {
            for (int i = 0; i < n - 1; i++)
                permute(acc + str.charAt(i), str.substring(0, i) + str.substring(i + 1, z), result, z);
        }
    }
}

Solution

  • This seems to work. Your edge condition is the problem.

    private static void permute(String acc, String str,Set<Integer> result,int z) {
        int n = str.length();
        if (acc.length() == z)
            result.add(Integer.parseInt(acc));
        else {
            for (int i = 0; i < n; i++)
                permute(acc + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n), result, z);
    
        }
    }
    
    System.out.println(maxDigit("1234", 2)); 
    43