I have a list of items {a,b,c,d} and I need to generate all possible combinations when,
If we take the possibilities, it should be,
n=4, number of items
total #of combinations = 4C4 + 4C3 + 4C2 + 4C1 = 15
I used the following recursive method:
private void countAllCombinations (String input,int idx, String[] options) {
for(int i = idx ; i < options.length; i++) {
String output = input + "_" + options[i];
System.out.println(output);
countAllCombinations(output,++idx, options);
}
}
public static void main(String[] args) {
String arr[] = {"A","B","C","D"};
for (int i=0;i<arr.length;i++) {
countAllCombinations(arr[i], i, arr);
}
}
Is there a more efficient way of doing this when the array size is large?
Consider the combination as a binary sequence, if all the 4 are present, we get 1111 , if the first alphabet is missing then we get 0111, and so on.So for n alphabets we'll have 2^n -1 (since 0 is not included) combinations.
Now, in your binary sequence produced, if the code is 1 , then the element is present otherwise it is not included. Below is the proof-of-concept implementation:
String arr[] = { "A", "B", "C", "D" };
int n = arr.length;
int N = (int) Math.pow(2d, Double.valueOf(n));
for (int i = 1; i < N; i++) {
String code = Integer.toBinaryString(N | i).substring(1);
for (int j = 0; j < n; j++) {
if (code.charAt(j) == '1') {
System.out.print(arr[j]);
}
}
System.out.println();
}
And here's a generic reusable implementation:
public static <T> Stream<List<T>> combinations(T[] arr) {
final long N = (long) Math.pow(2, arr.length);
return StreamSupport.stream(new AbstractSpliterator<List<T>>(N, Spliterator.SIZED) {
long i = 1;
@Override
public boolean tryAdvance(Consumer<? super List<T>> action) {
if(i < N) {
List<T> out = new ArrayList<T>(Long.bitCount(i));
for (int bit = 0; bit < arr.length; bit++) {
if((i & (1<<bit)) != 0) {
out.add(arr[bit]);
}
}
action.accept(out);
++i;
return true;
}
else {
return false;
}
}
}, false);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With