I'm referring to this question/answer: Permutation of N Lists (permutation of N lists to create all combinations of a search space). I implemented this for my case but having the problem to run out of memory as I work with a huge search space (currently millions or billions of combinations, increasing). This is my current code:
private void permute(List<List<T>> listOfLists, int index, Deque<T> tokens, boolean inMemory) {
if (index == listOfLists.size()) {
List<T> output = new LinkedList<>();
for (T item : tokens) {
output.add(item);
}
if (inMemory)
results.add(output);
else
writeToDisk(output);
} else {
List<T> types = listOfLists.get(index);
for (T l : types) {
tokens.addLast(l);
permute(listOfLists, index + 1, tokens, inMemory);
tokens.removeLast();
}
}
}
Where 'T' in my case is an Enum like
public enum LinkType implements Permutable { // Permutable -> Serializable Marker
L1(0.95f, 20), L2(0.85f, 12), L3(0.75f, 8);
protected final float reliability;
protected final int cost;
private LinkType(float reliability, int cost) {
this.reliability = reliability;
this.cost = cost;
}
public float getReliability() {
return reliability;
}
public int getCost() {
return cost;
}
}
My current problem is that the objects get written to disk but still reside in memory as it is necessary for the recursion. Any ideas to solve this problem? Increasing heap size is not a (permanent) solution as search space in my applications will definitely increase over time. Thank you very much for your help!
Edit: I know that I will never reach values above ~25 but I do not want to stuck already at 10!