我有一个元素列表(在java中),假设:
List<Integer> elem = new ArrayList<>();
elem.add(1);
elem.add(2);
elem.add(3);
elem.add(4);我只想遍历每一对独特的组合一次(这意味着我想要这6对:1,2; 1,3; 1,4; 2,3; 2,4; 3,4)
我这样做是这样的:
int i = 1;
for(Integer a:elem) {
for(int j = i; j<elem.size(); j++) {
Integer b = elem.get(j);
doSomethingWithCouple(a,b);
}
i++;
}“问题”是,我不太喜欢它。你知道更优雅/更简单的解决方案吗?谢谢
发布于 2013-05-08 09:19:10
只是把外部循环写成一个‘传统的’for for (i = 0; i < elems.size(); i++)循环。
for (i = 0; i < elems.size(); i++) {
for (j = i+1; j < elems.size(); j++) {
int ei = elems.get( i);
int ej = elems.get( j);
doSomethingWith( ei, ej);
}
}这是非常清晰的 --当然,获取ei可能会被挂起到外部循环,但代价是代码会变得不那么清晰。
发布于 2013-05-08 09:26:09
I found a library that will do this for you
package com.sandbox;
import org.paukov.combinatorics.Factory;
import org.paukov.combinatorics.Generator;
import org.paukov.combinatorics.ICombinatoricsVector;
public class Sandbox {
public static void main(String[] args) {
// Create the initial vector
ICombinatoricsVector<Integer> initialVector = Factory.createVector(
new Integer[]{1, 2, 3, 4});
// Create a simple combination generator to generate 3-combinations of the initial vector
Generator<Integer> gen = Factory.createSimpleCombinationGenerator(initialVector, 2);
// Print all possible combinations
for (ICombinatoricsVector<Integer> combination : gen) {
System.out.println(combination.getValue(0) + " " + combination.getValue(1));
}
}
}输出:
1 2
1 3
1 4
2 3
2 4
3 4https://stackoverflow.com/questions/16431126
复制相似问题