java - Improve the code of an algorithm of combinations -
i realized algorithm generating combinations. works in following way, if have input:
[a, b, c]
the combinations
[a], [b], [c]. [a, b], [a, c], [b, c], [a, b, c].
while if have in input:
[1,1,2,3]
the combinations be:
[1], [2], [3], [4], [1,2], [1,3], [2,3 ], [1,1,2,3].
however, algorithm has running time of when input list of size 4, if list of size 5 or more program stops , gives me java.lang.outofmemory
(i increased memory in java). 1 problem fact have used linkedlist
, i'm not sure.
is there better solution?
private list<elemento> combinazionemassima = new arraylist<>(); private log logger = logfactory.getlog(combinazioni3.class); public combinazioni3(list<elemento> generacombinazionemassima) { this.combinazionemassima = generacombinazionemassima; } public void combine() { this.findallcombinations(combinazionemassima); } private static class node{ int lastindex = 0; list<elemento> currentlist; public node(int lastindex, list<elemento> list) { this.lastindex = lastindex; this.currentlist = list; } public node(node n) { this.lastindex = n.lastindex; this.currentlist = new arraylist<elemento>(n.currentlist); } } public void findallcombinations(list<elemento> combinazioni) { date datainizio = new date(); list<list<elemento>> resultlist = new arraylist<list<elemento>>(); linkedlist<node> queue = new linkedlist<node>(); int n = combinazioni.size(); arraylist<elemento> temp = new arraylist<elemento>(); temp.add(combinazioni.get(0)); queue.add(new node(0, temp)); // add different integers queue once. for(int i=1;i<n;++i) { if(combinazioni.get(i-1) == combinazioni.get(i)) continue; temp = new arraylist<elemento>(); temp.add(combinazioni.get(i)); queue.add(new node(i, temp)); } // bfs until have no elements while(!queue.isempty()) { node node = queue.remove(); if(node.lastindex+1 < n) { node newnode = new node(node); newnode.lastindex = node.lastindex+1; newnode.currentlist.add(combinazioni.get(node.lastindex+1)); queue.add(newnode); } for(int i=node.lastindex+2;i<n;++i) { if(combinazioni.get(i-1) == combinazioni.get(i)) continue; // create copy , add integer node newnode = new node(node); newnode.lastindex = i; newnode.currentlist.add(combinazioni.get(i)); queue.add(newnode); } gestoreregole gestoreregole = new gestoreregole(); gestoreregole.esegui(node.currentlist); } }
Comments
Post a Comment