Combination Generator in JAVA

有些话、适合烂在心里 提交于 2019-12-24 03:44:01

问题


I am trying to find all combinations of items in several arrays. The number of arrays is random (this can be 2, 3, 4, 5...). The number of elements in each array is random too.

e.g., I have the 3 arrays :

String[][] array1 = {{"A1","A2","A3"},{"B1","B2","B3"},{"C1","C2"}};

I would like to generate an array with all possible combinations :

A1, B1, C1
A1, B1, C2
A1, B2, C1
A1, B2, C2
A1, B3, C1
A1, B3, C2
A2, B1, C1
A2, B1, C2 ...

回答1:


You could create the combinations by using a "counter-like" strategy, i.e. treat those arrays as digits of a number like this:

public static String[][] generateCombinations(String[]... arrays) {
    if (arrays.length == 0) {
        return new String[][]{{}};
    }
    int num = 1;
    for (int i = 0; i < arrays.length; i++) {
        num *= arrays[i].length;
    }

    String[][] result = new String[num][arrays.length];

    // array containing the indices of the Strings
    int[] combination = new int[arrays.length];

    for (int i = 0; i < num; i++) {
        String[] comb = result[i];
        // fill array
        for (int j = 0; j < arrays.length; j++) {
            comb[j] = arrays[j][combination[j]];
        }

        // generate next combination
        for (int j = arrays.length-1; j >= 0; j--) {
            int n = ++combination[j];
            if (n >= arrays[j].length) {
                // "digit" exceeded valid range -> back to 0 and continue incrementing
                combination[j] = 0;
            } else {
                // "digit" still in valid range -> stop
                break;
            }
        }
    }
    return result;
}

The method is called like this:

generateCombinations(
            new String[]{"A1","A2","A3"},
            new String[]{"B1","B2","B3"},
            new String[]{"C1","C2"}
       )

or like this:

generateCombinations(array1)



回答2:


There are two basic approaches to variable loop nesting. One is explicit bookkeeping, as discussed in the prior answer. The other is a recursive solution. In a recursive solution activations of the recursive method store as local variables the same index data as is tracked in an explicit array in the bookkeeping approach.

The base case for the recursion is to return a length 0 result array if the input contains zero arrays. If the input contains one or more arrays, generate the result from the elements of the first array and the recursive call result for the remaining arrays.



来源:https://stackoverflow.com/questions/30502830/combination-generator-in-java

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