Java排列&与没有订单的子列表组合

时间:2014-04-09 11:23:05

标签: java combinations permutation

我正在尝试用Java解决以下问题:

我有一个12个'Person'对象的列表(但是我们用整数来表示它们以简化计算)我想要创建所有可能的唯一组合。我在网上发现了足够的片段来帮助我(到目前为止我使用了this),但这是我无法弄清楚的部分:

该列表分为4个可变长度的子列表,其中顺序无关紧要。这些长度在int数组中定义,例如{3,4,2,3}。

在给定的示例中,原始列表可能如下所示:

{ 1,2,3, 4,5,6,7, 8,9, 10,11,12 }

如果这个是相同的,那么不应该计算:

{ 3,2,1, 7,6,5,4, 9,8, 12,11,10 }

我只想计算一个,因为首先计算每个组合然后排序所有子列表然后比较所有列表当然是非常不合格的。

PS:我找不到比这更好的头衔,这就是为什么我也没有成功搜索问题。建议将不胜感激: - )

1 个答案:

答案 0 :(得分:1)

我花了一些时间在上面并使用库来编写一些代码https://code.google.com/p/combinatoricslib/#3._Simple_combinations

打印出您需要的组合。我希望它有所帮助。

public class Test {

    static List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
    static int[] groups = new int[] { 3, 4, 2, 3 };

    public static void main(String[] args) throws Exception {
        print("", 0, list);
    }

    private static void print(String previousVector, int groupIndex, List<Integer> aList) {
        if (groupIndex == groups.length) { // last group
            System.out.println(previousVector);
            return;
        }

        ICombinatoricsVector<Integer> vector = Factory.createVector(aList.toArray(new Integer[0]));
        Generator<Integer> generator = Factory.createSimpleCombinationGenerator(vector, groups[groupIndex]);

        for (ICombinatoricsVector<Integer> combination : generator) {
            String vectorString = previousVector + combination.getVector().toString();
            List<Integer> copy = new LinkedList<>(aList);
            copy.removeAll(combination.getVector());
            print(vectorString, groupIndex + 1, copy); 
        }
    }
}