Compare every item to every other item in ArrayList

后端 未结 5 878
孤街浪徒
孤街浪徒 2021-02-05 08:07

I\'m having trouble with what I thought should be a pretty simple problem.

I need to compare every item in an arrayList with every other item in the the list without com

5条回答
  •  不思量自难忘°
    2021-02-05 08:19

    This code helped me get this behaviour: With a list a,b,c, I should get compared ab, ac and bc, but any other pair would be excess / not needed.

    import java.util.*;
    import static java.lang.System.out;
    
    // rl = rawList; lr = listReversed
    ArrayList rl = new ArrayList();
    ArrayList lr = new ArrayList();
    rl.add("a");
    rl.add("b");
    rl.add("c");
    rl.add("d");
    rl.add("e");
    rl.add("f");
    
    lr.addAll(rl);
    Collections.reverse(lr);
    
    for (String itemA : rl) {
        lr.remove(lr.size()-1);
            for (String itemZ : lr) {
            System.out.println(itemA + itemZ);
        }
    }
    

    The loop goes as like in this picture: Triangular comparison visual example

    or as this:

       |   f    e    d    c    b   a
       ------------------------------
    a  |  af   ae   ad   ac   ab   ·
    b  |  bf   be   bd   bc   ·   
    c  |  cf   ce   cd   ·      
    d  |  df   de   ·         
    e  |  ef   ·            
    f  |  ·               
    

    total comparisons is a triangular number (n * n-1)/2

提交回复
热议问题