I need to compute and get all the permutations for a large number. Like an array which contains 13 numbers. But though the code I found from the internet worked for 10 values , for 13 numbers it doesn't work as I got an Exception. It says the memory is not enough to show the total permutations. I do not need to print the permutations. For me storing them in the database will be perfectly oki. Still can't I do the calculation if I directly store them in the database. I couldn't find a proper answer for this from internet.
This is the code I used to calculate the permutations.
public class PermutationCalc {
/**
* @param args the command line arguments
*/
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,5,6,7,8,9,10} );
System.gc();
for ( Integer[] p : int_perms ) System.out.println( arrayToString( p ) );
}
}
Can someone please let me know whether I would be able to solve it if I store them in a database and calculate.
PS: Is there another efficient code that I can use in finding 13! of permutation values.