The objective is simple: List all possible permutations for a given a String. I looked at some implementations from popular sources. I decided to build this to the flow:
The Code for Review
package com.progint;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
public class StringPermutations {
public static ArrayList<String> permutations = new ArrayList<String>();
public static String permutand;
public static ArrayList<String> permuteString() {
permutations = permuteString(permutand);
return permutations;
}
public static ArrayList<String> permuteString(String permutand) {
ArrayList<String> listOfPermutations = new ArrayList<String>();
if(permutand.length()==1) {
listOfPermutations.add(permutand);
return listOfPermutations;
}
/* Iterate over All character Values */
for (int i=0; i<permutand.length(); i++) {
String nextStringPermutation;
if (i==0) { /* All characters following need to be permuted */
nextStringPermutation = permutand.substring(i+1);
}
else { /* All characters--not including the current base character-- need to be permuted */
nextStringPermutation = "".concat(permutand.substring(0,i));
if(i+1 < permutand.length()) {
nextStringPermutation = nextStringPermutation.concat(permutand.substring(i+1));
}
}
/* Retrieve list of possible sub-permutations and build a list with all possibilities */
ArrayList<String> innerListOfPermutations = permuteString(nextStringPermutation);
for (String permutation : innerListOfPermutations)
listOfPermutations.add(permutand.substring(i,i+1).concat(permutation));
}
return listOfPermutations;
}
public static void main(String[] args) throws IOException {
ArrayList<String> permutations;
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string to permute");
permutand = consoleReader.readLine();
permutations = permuteString();
System.out.println("The " + permutations.size() + " permutations are:");
for(String permutation : permutations) {
System.out.println(permutation);
}
}
}
I get a 'tarot deck being shuffled' vibe with this implementation.
My Inspirations (for Comparison)
The below is from Programming Interviews Exposed:
void permute(String str){ int length = str.length(); boolean[] used = new boolean[length]; StringBuffer out = new StringBuffer(); char[] in = str.toCharArray(); doPermute(in, out, used, length, 0); } void doPermute(char[] in, StringBuffer out, boolean[] used, int length, int level) { if( level == length ){ System.out.println( out.toString() ); return; } for(int i = 0; i < length; ++i ){ if(used[i]) continue; out.append(in[i]); used[i] = true; doPermute( in, out, used, length, level + 1 ); used[i] = false; out.setLength(out.length()-1); } }
I also looked at this very concise implementation based on swapping.