【问题标题】:Java permutation & combination with sublist without orderJava排列组合与子列表无序
【发布时间】:2014-04-09 11:23:04
【问题描述】:

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

我有一个包含 12 个“Person”对象的列表(但让我们用整数表示它们以简化计算),我想创建所有可能的唯一组合。我在网上找到了足够多的 sn-ps 来帮助我解决这个问题(到目前为止,我使用了 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:我找不到比这更好的标题了,这也是我在谷歌上搜索问题的原因。建议将不胜感激:-)

【问题讨论】:

  • 组合的总数不是Person对象的阶乘吗? 12!
  • @user3514900 所以假设你有列表 [1, 2, 3] 你想要答案是 [], [1], [2], [3], [1, 2 ], [1,3], [2, 3], [1, 2, 3]?
  • Person 对象将是 12 个唯一对象吗?
  • @onesixtyfourth 那是排列。根据 OP 的要求,他们可能误用了 combinations 一词。
  • 基本上 OP 所要做的就是使所有集合的大小从 1 到 9 个元素与数字 1 到 12 的组合(元素顺序无关紧要),然后必须使每个可能的 4 个插槽组合从他之前制作的那些套装

标签: java combinations permutation


【解决方案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); 
        }
    }
}

【讨论】:

  • 看来这些确实是正确的组合!不过,我需要一些时间来弄清楚代码,但我并不像您可能注意到的那样经验丰富。非常感谢!
猜你喜欢
  • 2014-08-08
  • 1970-01-01
  • 2012-08-12
  • 1970-01-01
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 2018-05-22
相关资源
最近更新 更多