I have an string array
{\"ted\", \"williams\", \"golden\", \"voice\", \"radio\"}
and I want all possible combinations of these keywords in
EDIT: As FearUs pointed out, a better solution is to use Guava's Sets.powerset(Set set).
EDIT 2: Updated links.
Quick and dirty translation of this solution:
public static void main(String[] args) {
List> powerSet = new LinkedList>();
for (int i = 1; i <= args.length; i++)
powerSet.addAll(combination(Arrays.asList(args), i));
System.out.println(powerSet);
}
public static List> combination(List values, int size) {
if (0 == size) {
return Collections.singletonList(Collections. emptyList());
}
if (values.isEmpty()) {
return Collections.emptyList();
}
List> combination = new LinkedList>();
T actual = values.iterator().next();
List subSet = new LinkedList(values);
subSet.remove(actual);
List> subSetCombination = combination(subSet, size - 1);
for (List set : subSetCombination) {
List newSet = new LinkedList(set);
newSet.add(0, actual);
combination.add(newSet);
}
combination.addAll(combination(subSet, size));
return combination;
}
Test:
$ java PowerSet ted williams golden
[[ted], [williams], [golden], [ted, williams], [ted, golden], [williams, golden], [ted, williams, golden]]
$