Skip to content

Instantly share code, notes, and snippets.

@scottashipp
Created August 5, 2016 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottashipp/33247d66ccdf0ce14bb19fd813d7b217 to your computer and use it in GitHub Desktop.
Save scottashipp/33247d66ccdf0ce14bb19fd813d7b217 to your computer and use it in GitHub Desktop.
Permutations Generator in Java....not as good as Scala
import java.util.ArrayList;
import java.util.Scanner;
public class PermutationGenerator1 {
private static String inputWithoutC(String input, char c) {
String inputWithoutC = "";
char[] temp = input.toCharArray();
for(char d : temp) {
if(d !=c ) {
inputWithoutC += d;
}
}
return inputWithoutC;
}
private static ArrayList<String> generatePermutationsOfAString(String input) {
if(input == null) {
return null;
}
ArrayList<String> subPermutations = new ArrayList<>();
ArrayList<String> permutations = new ArrayList<>();
//base case: one letter, just return it
if(input.length() == 1) {
permutations.add(input);
return permutations;
}
char[] temp = input.toCharArray();
for(char c : temp) {
String subChars = inputWithoutC(input,c);
subPermutations = generatePermutationsOfAString(subChars);
for(String s : subPermutations) {
permutations.add(String.valueOf(c) + s);
}
}
return permutations;
}
public static void main(String[] args) {
Scanner readUserInput = new Scanner(System.in);
System.out.println("Enter the source string: ");
String combineThis = readUserInput.next();
ArrayList<String> xs = generatePermutationsOfAString(combineThis);
System.out.println("There were " + xs.size()+ " results found.");
System.out.println("\nThe resulting permutations are: ");
for(String s : xs) {
System.out.println(s + "\t");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment