I have a working example to generate all char permutations in a String as below:
static ArrayList permutations(String s) {
if (s == nul
Here you go, the below sample code uses the recursive method to get the permutation. It is generic and you can specify the output location as you like. One bonus is you can specify delimiter as well.
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Permutation {
//The entry of the permutation method
public static <T> List<T[]> permute(T[] arr){
List<T[]> result = new ArrayList<T[]>();
permute(new ArrayList<T>(), Arrays.asList(arr), result);
return result;
}
//This is the actual method doing the permutation
private static <T> void permute(List<T> pre, List<T> cur, List<T[]> out){
int size = cur.size();
if(size == 0){
out.add((T[])pre.toArray());
} else {
for(int i=0; i<size; ++i){
List<T> tmpPre = new ArrayList<T>(pre);
List<T> tmpCur = new ArrayList<T>(cur);
tmpPre.add(cur.get(i));
tmpCur.remove((T)cur.get(i));
permute(tmpPre, tmpCur, out);
}
}
}
//Print each row of the permutated values
private static <T> void print(List<T[]> list, OutputStream out, char delim){
try{
for(T[] i : list){
int count = 0;
for(T t : i){
if(++count == i.length){
out.write((t.toString()).getBytes());
} else{
out.write((t.toString()+delim).getBytes());
}
}
out.write("\n".getBytes());
}
} catch (Exception ex){
ex.printStackTrace();
}
}
public static void main(String[] args) throws FileNotFoundException {
Integer[] ints = new Integer[] {1, 2, 3, 4};
Permutation.print(Permutation.permute(ints), System.out, ',');
Character[] chars = {'a', 'b', 'c', 'd', 'e'};
Permutation.print(Permutation.permute(chars), new PrintStream("permute.txt"), ' ');
String[] strs = {"abc", "123"};
Permutation.print(Permutation.permute(strs), System.err, ' ');
}
}
Here is my solution (gist):
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* @author Karol Krol
*/
public class Permutation {
private Permutation() {
}
public static List<List<Integer>> permutation(final int[] numbers) {
final PermutationCollector permutationCollector = new PermutationCollector();
permutation(new int[0], numbers, permutationCollector);
return permutationCollector.getResult();
}
private static void permutation(int[] prefix, int[] array, final Consumer<int[]> operation) {
int length = array.length;
if (length == 0) {
operation.accept(prefix);
} else {
for (int i = 0; i < length; ++i) {
final int[] newPrefix = append(prefix, array[i]);
final int[] reducedArray = reduce(array, i);
permutation(newPrefix, reducedArray, operation);
}
}
}
private static int[] append(int[] array, int element) {
int newLength = array.length + 1;
array = Arrays.copyOf(array, newLength);
array[newLength - 1] = element;
return array;
}
private static int[] reduce(int[] array, int index) {
final int newLength = array.length - 1;
if (index == 0) {
return Arrays.copyOfRange(array, 1, array.length);
} else {
final int[] dest = new int[newLength];
System.arraycopy(array, 0, dest, 0, index);
System.arraycopy(array, index + 1, dest, index, newLength - index);
return dest;
}
}
public static class PermutationCollector implements Consumer<int[]> {
private List<List<Integer>> result = new ArrayList<>();
@Override
public void accept(int[] ints) {
result.add(IntStream.of(ints).boxed().collect(Collectors.toList()));
}
public List<List<Integer>> getResult() {
return result;
}
}
}
Below is a class containing a solution using generics. The API is a bit different then what you specified but far more flexible. Easiest to see with examples. Note that the inputs probably have more constraints than what I'm checking here!
public static final class Permutations {
private Permutations() {}
public static <T> List<T[]> get(Class<T> itemClass, T... itemsPool) {
return get(itemsPool.length, itemClass, itemsPool);
}
public static <T> List<T[]> get(int size, Class<T> itemClass, T... itemsPool) {
if (size < 1) {
return new ArrayList<T[]>();
}
int itemsPoolCount = itemsPool.length;
List<T[]> permutations = new ArrayList<T[]>();
for (int i = 0; i < Math.pow(itemsPoolCount, size); i++) {
T[] permutation = (T[]) Array.newInstance(itemClass, size);
for (int j = 0; j < size; j++) {
// Pick the appropriate item from the item pool given j and i
int itemPoolIndex = (int) Math.floor((double) (i % (int) Math.pow(itemsPoolCount, j + 1)) / (int) Math.pow(itemsPoolCount, j));
permutation[j] = itemsPool[itemPoolIndex];
}
permutations.add(permutation);
}
return permutations;
}
}
Example Usage
Calling Permutations.get(2, Integer.class, 1, 0, -1);
will return the following list of integer arrays:
[ 1, 1]
[ 0, 1]
[-1, 1]
[ 1, 0]
[ 0, 0]
[-1, 0]
[ 1, -1]
[ 0, -1]
[-1, -1]
Calling Permutations.get(3, Integer.class, 1, 0, -1);
will return the following list of integer arrays. Note that this example is identical to the first except for the first argument which is now 3:
[ 1, 1, 1]
[ 0, 1, 1]
[-1, 1, 1]
[ 1, 0, 1]
[ 0, 0, 1]
[-1, 0, 1]
[ 1, -1, 1]
[ 0, -1, 1]
[-1, -1, 1]
[ 1, 1, 0]
[ 0, 1, 0]
[-1, 1, 0]
[ 1, 0, 0]
[ 0, 0, 0]
[-1, 0, 0]
[ 1, -1, 0]
[ 0, -1, 0]
[-1, -1, 0]
[ 1, 1, -1]
[ 0, 1, -1]
[-1, 1, -1]
[ 1, 0, -1]
[ 0, 0, -1]
[-1, 0, -1]
[ 1, -1, -1]
[ 0, -1, -1]
[-1, -1, -1]