I have a working example to generate all char permutations in a String as below:
static ArrayList permutations(String s) {
if (s == nul
I've written that code some time ago, and edited a bit to match your requests. I hope it works.
static ArrayList<String> permutations(String s) {
ArrayList<String> ret = new ArrayList<String>();
permutation(s.toCharArray(), 0, ret);
return ret;
}
public static void permutation(char[] arr, int pos, ArrayList<String> list){
if(arr.length - pos == 1)
list.add(new String(arr));
else
for(int i = pos; i < arr.length; i++){
swap(arr, pos, i);
permutation(arr, pos+1, list);
swap(arr, pos, i);
}
}
public static void swap(char[] arr, int pos1, int pos2){
char h = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = h;
}
UPDATE
I just tried it on ideone.com. It seems to work. You're welcome. :)
UPDATE 2
It should basically be the same code with arrays of int's:
static ArrayList<int[]> permutations(int[] a) {
ArrayList<int[]> ret = new ArrayList<int[]>();
permutation(a, 0, ret);
return ret;
}
public static void permutation(int[] arr, int pos, ArrayList<int[]> list){
if(arr.length - pos == 1)
list.add(arr.clone());
else
for(int i = pos; i < arr.length; i++){
swap(arr, pos, i);
permutation(arr, pos+1, list);
swap(arr, pos, i);
}
}
public static void swap(int[] arr, int pos1, int pos2){
int h = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = h;
}
UPDATE 3
Works with int's too: http://ideone.com/jLpZow
//Here is a recursive version that was not to hard to commit to human memory ! O(n!) permutations.
public static Set<Integer[]> getPermutationsRecursive(Integer[] num){
if (num == null)
return null;
Set<Integer[]> perms = new HashSet<>();
//base case
if (num.length == 0){
perms.add(new Integer[0]);
return perms;
}
//shave off first int then get sub perms on remaining ints.
//...then insert the first into each position of each sub perm..recurse
int first = num[0];
Integer[] remainder = Arrays.copyOfRange(num,1,num.length);
Set<Integer[]> subPerms = getPermutationsRecursive(remainder);
for (Integer[] subPerm: subPerms){
for (int i=0; i <= subPerm.length; ++i){ // '<=' IMPORTANT !!!
Integer[] newPerm = Arrays.copyOf(subPerm, subPerm.length+1);
for (int j=newPerm.length-1; j>i; --j)
newPerm[j] = newPerm[j-1];
newPerm[i]=first;
perms.add(newPerm);
}
}
return perms;
}
This code takes String elements, but can me modified to work for integers:
import java.util.*;
/**
* Write a description of class GeneratePermutations here.
*
* @author Kushtrim
* @version 1.01
*/
public class GeneratePermutations
{
public static void main(String args[])
{
GeneratePermutations g = new GeneratePermutations();
String[] elements = {"a","b","c",};
ArrayList<String> permutations = g.generatePermutations(elements);
for ( String s : permutations)
{
System.out.println(s);
}
//System.out.println(permutations.get(999999));
}
private ArrayList<String> generatePermutations( String[] elements )
{
ArrayList<String> permutations = new ArrayList<String>();
if ( elements.length == 2 )
{
String x1 = elements[0] + elements[1];
String x2 = elements[1] + elements[0];
permutations.add(x1);
permutations.add(x2);
}
else {
for ( int i = 0 ; i < elements.length ; i++)
{
String[] elements2 = new String[elements.length -1];
int kalo = 0;
for( int j =0 ; j< elements2.length ; j++ )
{
if( i == j)
{
kalo = 1;
}
elements2[j] = elements[j+kalo];
}
ArrayList<String> k2 = generatePermutations(elements2);
for( String x : k2 )
{
String s = elements[i]+x;
permutations.add(s);
}
}
}
return permutations;
}
}
By adding a TreeSet it removes duplicates and sorts the permutations.
package permutations;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;
public class Permutations {
public static void main(String args[])
{
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.println("This application accepts input of a string and creates a list of all possible permutations\n\r");
System.out.println("Please Enter a string of characters");
String input = scanner.nextLine();
String[] elements = input.split("");
Permutations g = new Permutations();
ArrayList<String> permutations = g.generatePermutations(elements);
TreeSet ts = new TreeSet();
for ( String s : permutations)
{
//System.out.println(s);
ts.add(s);
}
System.out.println("List of all possible permutations");
System.out.println(ts);
}
private ArrayList<String> generatePermutations( String[] elements )
{
ArrayList<String> permutations = new ArrayList<String>();
if ( elements.length == 2 )
{
String x1 = elements[0] + elements[1];
String x2 = elements[1] + elements[0];
permutations.add(x1);
permutations.add(x2);
}
else {
for ( int i = 0 ; i < elements.length ; i++)
{
String[] elements2 = new String[elements.length -1];
int kalo = 0;
for( int j =0 ; j< elements2.length ; j++ )
{
if( i == j)
{
kalo = 1;
}
elements2[j] = elements[j+kalo];
}
ArrayList<String> k2 = generatePermutations(elements2);
for( String x : k2 )
{
String s = elements[i]+x;
permutations.add(s);
}
}
}
return permutations;
}
}
import java.util.ArrayList;
import java.util.Arrays;
public class Answer {
static <E> String arrayToString( E[] arr ) {
final StringBuffer str = new StringBuffer();
for ( E e : arr )
str.append( e.toString() );
return str.toString();
}
static <E> ArrayList<E[]> permutations(E[] arr) {
final ArrayList<E[]> resultList = new ArrayList<E[]>();
final int l = arr.length;
if ( l == 0 ) return resultList;
if ( l == 1 )
{
resultList.add( arr );
return resultList;
}
E[] subClone = Arrays.copyOf( arr, l - 1);
System.arraycopy( arr, 1, subClone, 0, l - 1 );
for ( int i = 0; i < l; ++i ){
E e = arr[i];
if ( i > 0 ) subClone[i-1] = arr[0];
final ArrayList<E[]> subPermutations = permutations( subClone );
for ( E[] sc : subPermutations )
{
E[] clone = Arrays.copyOf( arr, l );
clone[0] = e;
System.arraycopy( sc, 0, clone, 1, l - 1 );
resultList.add( clone );
}
if ( i > 0 ) subClone[i-1] = e;
}
return resultList;
}
static ArrayList<String> permutations(String arr) {
final Character[] c = new Character[ arr.length() ];
for ( int i = 0; i < arr.length(); ++i )
c[i] = arr.charAt( i );
final ArrayList<Character[]> perms = permutations(c);
final ArrayList<String> resultList = new ArrayList<String>( perms.size() );
for ( Character[] p : perms )
{
resultList.add( arrayToString( p ) );
}
return resultList;
}
public static void main(String[] args) {
ArrayList<String> str_perms = permutations( "abc" );
for ( String p : str_perms ) System.out.println( p );
ArrayList<Integer[]> int_perms = permutations( new Integer[]{ 1, 2, 3, 4 } );
for ( Integer[] p : int_perms ) System.out.println( arrayToString( p ) );
}
}
/**
*
* @param startIndex is the position of the suffix first element
* @param prefix is the prefix of the pattern
* @param suffix is the suffix of the pattern, will determine the complexity
* permute method.
*
*
* The block <code>if (suffix.length == 1)</code> will print
* the only possible combination of suffix and return for computing next
* combination.
*
*
* The part after <code>if (suffix.length == 1)</code> is reached if suffix
* length is not 1 that is there may be many possible combination of suffix
* therefore make a <code>newSuffix</code> which will have suffix length
* <code>(suffix.length - 1)</code> and recursively compute the possible
* combination of this new suffix and also the original suffix prefix
* positioned by <code>startIndex</code> will change by increasing its value
* by one <code>(startIndex + 1) % suffix.length</code>
*
*
* T(N) = N * T(N - 1) + N
* = N! + N!(1 + 1/N + 1/(N * (N - 1)) + ... + 1/N!)
*
*
*/
public static void permute(int startIndex, int prefix[], int suffix[]) {
if (suffix.length == 1) {
for (int i = 0; i < prefix.length; i++) {
System.out.print(prefix[i] + " ");
}
System.out.print(suffix[0]);
System.out.println(" ");
return;
}
for (int i = 0; i < suffix.length; i++) {
counter++;
int newPrefix[] = new int[prefix.length + 1];
System.arraycopy(prefix, 0, newPrefix, 0, prefix.length);
newPrefix[prefix.length] = suffix[startIndex];
int newSuffix[] = new int[suffix.length - 1];
for (int j = 1; j < suffix.length; j++) {
newSuffix[j - 1] = suffix[(startIndex + j) % suffix.length];
}
permute((startIndex % newSuffix.length), newPrefix, newSuffix);
startIndex = (startIndex + 1) % suffix.length;
}
}