mercredi 25 février 2015

Avoiding an OutOfMemoryError



I recently made a method in Java to get the permutation of a string but it's throwing this when the string is too long: java.lang.OutOfMemoryError: Java heap space I'm sure that the method is efficient so I need advice on how to spread the calculations to avoid the error. I'm running it using the console in Eclipse.



public static ArrayList<String> permutation(String s) {
ArrayList<String> res = new ArrayList<String>();
if (s.length() == 1) {
res.add(s);
} else if (s.length() > 1) {
int lastIndex = s.length() - 1;
String last = s.substring(lastIndex);
String rest = s.substring(0, lastIndex);
res = merge(permutation(rest), last);
}
return res;
}
public static int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
public static ArrayList<String> merge(ArrayList<String> list, String c) {
ArrayList<String> res = new ArrayList<String>();
for (String s : list) {
for (int i = 0; i <= s.length(); ++i) {
String ps = new StringBuffer(s).insert(i, c).toString();
res.add(ps);
}
}
return res;
}


Greets, Robin




Aucun commentaire:

Enregistrer un commentaire