My algorithm generates permutations of the number 0...n, where n can be any number from 1 to 9. it works perfectly for numbers from 1 to 8. But when I run it with 9, it runs for a while. Then suddenly aborts the process and exits... with no error message or any such thing! I have been coding in java for quite a while and have never experienced this error.
My algorithm:-
package utils;
import java.util.ArrayList;
class Lexicography {
static ArrayList<Long> perms = new ArrayList<Long>();
public static void main(String[] args){
long time = System.currentTimeMillis();
getPermutations(Integer.valueOf(args[0]));
System.out.println("\nSize:-"+perms.size()+"\nTime:-"+(System.currentTimeMillis()-time));
//This println is never printed... java aborts before that
}
public static ArrayList<Long> getPermutations(int num){
int[] n = new int[num+1];
for(int i=0; i<=num; i++) n[i]=i;
perms.add(getLong(n));
for(int i=num; i>=0; i--) permutate(n[i],n);
return perms;
}
private static void permutate(int k, int[] n){
if(k>n.length) return;
int p=0;
for(int i:n){ if(i==k) break; p++;}
for(int i=0; i<n.length; i++){
if(i==p || n[i]<k) continue;
n=swap(p,i,n);
perms.add(getLong(n));
System.out.println("i:"+(i+1)+" k:"+k+" n:"+getLong(n));//this prints all permutations till the last one and then poof!
for(int j=k-1; j>=0; j--) permutate(j,n);
n=swap(p,i,n);
}
}
private static int[] swap(int i, int f, int[] a){
int t=a[f];
a[f]=a[i]; a[i]=t;
return a;
}
private static long getLong(int[] n){
long ten=1, num=0;
for(int i=n.length-1; i>=0; i--){
num+=n[i]*ten; ten*=10;
}
return num;
}
}
Without the print statement, this runs pretty fast for numbers till 8 (for 8 it runs under 280ms). But for 9 it just stops suddenly after printing the last permutation. Can someone please help? Thank you!
Size:-3628800 Time:-104847Longs takes up too much memory? See ideone.com/67764E