I have the following Python function to recursively find all partitions of a set:
def partitions(set_):
if not set_:
yield []
return
for i in xrange(2**len(set_)/2):
parts = [set(), set()]
for item in set_:
parts[i&1].add(item)
i >>= 1
for b in partitions(parts[1]):
yield [parts[0]]+b
for p in partitions(["a", "b", "c", "d"]):
print(p)
Can someone help me to translate this into Java? This is what I have so far:
private static List<List<List<String>>> partitions(List<String> inputSet) {
List<List<List<String>>> res = Lists.newArrayList();
if (inputSet.size() == 0) {
List<List<String>> empty = Lists.newArrayList();
res.add(empty);
return res;
}
int limit = (int)(Math.pow(2, inputSet.size())/2);
for (int i = 0; i<limit; i++) {
List<List<String>> parts = Lists.newArrayList();
List<String> part1 = Lists.newArrayList();
List<String> part2 = Lists.newArrayList();
parts.add(part1);
parts.add(part2);
for (String item: inputSet) {
parts.get(i&1).add(item);
i >>= 1;
}
for (List<List<String>> b: partitions(parts.get(1))) {
List<List<String>> set = Lists.newArrayList();
set.add(parts.get(0));
set.addAll(b);
res.add(set);
}
}
return res;
}
I get an infinite recursion when executing it with more than one element.
A post similar to this one (with Ruby) can be found here. The original Python code can be found here and here.