org.archive.util.CrossProduct Maven / Gradle / Ivy
package org.archive.util;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Stack;
public class CrossProduct {
public List> crossProduct(List> listOfLists) {
ArrayList> results = new ArrayList>();
Stack current = new Stack();
Deque> remainder = new ArrayDeque>(listOfLists);
recurse(remainder,current,results);
return results;
}
private void recurse(Deque> remainder,
Stack current, ArrayList> accumulation) {
if(remainder.isEmpty()) {
// all done:
dump(new ArrayList(current));
accumulation.add(new ArrayList(current));
} else {
List cur = remainder.removeFirst();
for(T o : cur) {
current.push(o);
recurse(remainder,current,accumulation);
current.pop();
}
remainder.addFirst(cur);
}
}
private void dump(ArrayList a) {
StringBuilder sb = new StringBuilder();
boolean first = false;
for(T o : a) {
if(first) {
first = false;
} else {
sb.append(",");
}
sb.append(o.toString());
}
System.out.println("CrossOutput:" + sb.toString());
}
}