本文介绍了JAVA组合生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到几个数组中的项目的所有组合。数组的数量是随机的(这可以是2,3,4,5 ...)。

例如,我有3个数组:

<$ p $ array1 = {{A1,A2,A3},{B1,B2,B3},{C1, C2\" }};

我想用所有可能的组合生成一个数组:

解决方案

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)

这篇关于JAVA组合生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 00:30