Question

For a given Collection<Object> aCollection, How do I build an ArrayList<OrderedCouple<Object>> with all possible permutations of couples in aCollection (except self-coupling).

For instance, say aCollection is a Set<Team> containing teamA, teamB and teamC, and OrderedCouple is instead a class Game<Team> which constructor receives two team, the host and the guest as arguments. I want to build an ArrayList of all possible Games between Teams. that is, the ArrayList will be the group {new Game(teamA, teamB), new Game(teamA, teamC), new Game(teamB, teamA), new Game(teamB, teamC), new Game(teamC, teamA), new Game(teamC, teamB)} in a random order.

Was it helpful?

Solution

I can't think of a faster way than this:

@Test
public void buildMatchUps() {
    List<String> teams = Arrays.asList("A", "B", "C");
    int s = teams.size() * teams.size() - teams.size();
    List<String> matchUps = new ArrayList<String>(s);
    for(String host : teams) {
        for(String guest : teams) {
            if(host != guest) { // ref comparison, because the objects
                                // come from the same list. Otherwise
                                // equals should be used!
                matchUps.add(host + " : " + guest);
            }
        }
    }
    Collections.shuffle(matchUps);
    for(String matchUp : matchUps) {
        System.out.println(matchUp);
    }
}

prints something like this:

C : A
B : A
A : C
C : B
B : C
A : B
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top