2013-05-08 34 views
0

我有元素(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++; 
} 

“问题”是,我不喜欢它非常。你知道一些更优雅/简单的解决方案吗? 谢谢

+0

是什么的'doSomethingWithCouple(A,B)的代码;'? – 2013-05-08 01:19:17

+0

相关:http://stackoverflow.com/questions/9453074/generating-all-unique-pairs-from-a-list-of-numbers-n-choose-2 – berry120 2013-05-08 01:19:19

回答

4

只能将外循环写为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可以提升到外环,在代码变得稍微不太清楚成本。

0

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 4