Generate All Possible Combinations - Java [duplicate]

爱⌒轻易说出口 提交于 2019-12-04 19:28:20

问题


I have a list of items {a,b,c,d} and I need to generate all possible combinations when,

  • you can select any number of items
  • the order is not important (ab = ba)
  • empty set is not considered

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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/37835286/generate-all-possible-combinations-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!