Skip to content

Instantly share code, notes, and snippets.

@MrMikeFloyd
Created January 8, 2020 12:05
Show Gist options
  • Save MrMikeFloyd/4dd191be285944b4f4cd1b735bdcf95c to your computer and use it in GitHub Desktop.
Save MrMikeFloyd/4dd191be285944b4f4cd1b735bdcf95c to your computer and use it in GitHub Desktop.
A little Java command line program that finds all permutations for a given String using recursive calls.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
class PermutationsFinder {
public static void main(String[] args) throws IOException {
String input;
ArrayList<String> permutations = new ArrayList<>();
System.out.println("Please enter a String: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
// call the main program - the left string will be empty as we don't have any characters from a previous call
permute(permutations, "", input);
System.out.println("Number of permutations for the supplied String: " + permutations.size());
System.out.println("Permutations:");
for (Object permutation : permutations) {
System.out.println(permutation);
}
}
/**
* Finds all permutations for a given String.
*
* @param permutations a list storing the results
* @param leftString the characters from previous calls + the character at the loop's current position
* @param rightString the remainder of the string on the right hand side
*/
private static void permute(ArrayList<String> permutations, String leftString, String rightString) {
if (rightString.length() <= 1) {
// base case: Our string only contains a single character
// the result string is composed of both the left and the right string
permutations.add(leftString + rightString);
} else {
// base case condition is not met - split String and increase recursion depth
for (int i = 0; i < rightString.length(); i++) {
try {
// the left portion of the String stores the character at the loop's current position
String leftStringRek = Character.toString(rightString.charAt(i));
// the right portion stores the remaining characters
// by doing this, the right string is reduced by 1 character with every recursive call
String rightStringRek = rightString.substring(0, i) + rightString.substring(i + 1);
// perform recursive call
permute(permutations, leftString + leftStringRek, rightStringRek);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment