Algorithm Interview Report
- 0of 0 votes
Answersmy algorithm generates combinations of elements . For example having [A , B , C ] creates the following combinations [ A] , [ B ] , [ C ] , [ AB ] , [ AC ] , [ B , C ] , [ ABC ] . Unfortunately for items too large too long and too much memory space . So many times I java.lang.OutOfMemory launches . How can I fix ?
- pasquale.restaino1992 July 06, 2015 in United States
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 List<List<Elemento> > 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 all different integers to the 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));
}
// do bfs until we 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 a copy and add extra 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);
}
Date dataF = new Date();
long tempo = dataF.getTime() - dataInizio.getTime();
logger.info ("durata genera combinazioni: " + tempo);
return resultList;| Report Duplicate | Flag | PURGE
Algorithm - 0of 0 votes
AnswersHello , I must write a program that given the elements in a list , generates all combinations of these elements .
- pasquale.restaino1992 July 06, 2015 in United States
For example, if I [A, B , C ] , the possible combinations are [ A] , [B ] , [ C ] , [A, B ] . [ A, C ] , [ B, C ] , [A, B , C ] . Another example , having [ A, A, B] the possible combinations are [ A] , [ A, A ] , [A, B ] , [ A, A, B, A ] .
How can I write it in java ?| Report Duplicate | Flag | PURGE
Java