我正在尝试用 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:我找不到比这更好的标题,这就是为什么我也没有成功地用谷歌搜索这个问题。如有建议,我们将不胜感激:-)
最佳答案
我花了一些时间,并使用组合库编写了一些代码 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);
}
}
}
关于Java 子列表无序排列组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22960974/