I have an string array
{\"ted\", \"williams\", \"golden\", \"voice\", \"radio\"}
and I want all possible combinations of these keywords in
My optimized solution is based on the solution provided by Matthew McPeak. This version avoids unnecessary array copies.
public static T[][] combinations(T[] a) {
int len = a.length;
if (len > 31)
throw new IllegalArgumentException();
int numCombinations = (1 << len) - 1;
@SuppressWarnings("unchecked")
T[][] combinations = (T[][]) java.lang.reflect.Array.newInstance(a.getClass(), numCombinations);
// Start i at 1, so that we do not include the empty set in the results
for (int i = 1; i <= numCombinations; i++) {
@SuppressWarnings("unchecked")
T[] combination = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(),
Integer.bitCount(i));
for (int j = 0, ofs = 0; j < len; j++)
if ((i & (1 << j)) > 0)
combination[ofs++] = a[j];
combinations[i - 1] = combination;
}
return combinations;
}