Join two Arraylist

Asked

Viewed 935 times

1

I made a ArrayList (nomeTimes) which receives a number of team names as per the for down below:

  for(int i = 0; i<numeroTimes;i++){
        String nomeTime=entrada.next();
        nomeTimes.add(nomeTime);
    }

My idea is to duplicate this ArrayList and shuffle with:

Collections.shuffle(nomeTimes);

And put the two together Arraylists in a third.

In this case it is to assemble a table with the confrontations of the teams. The confrontations stored in the third ArrayList would look like this: [[a,b][a,c][a,d],[[b,a],[b,c],[b,d]].

How to unite the two in a third?

  • 1

    Do you want to assemble an Arraylist that has the confrontations? Could you tell us how you expect each String to look in this third Arraylist?

  • This, I thought for example, 4 teams, and everyone plays with each other, would be like [[a,b][a,c][a,d],[[b,c],[b,d]] and so on, I think it would be better to manipulate or complicate too much?

1 answer

5


I thought, Instead of having two ArrayListYou only need one, which has the name of the teams. Then you make a permutation 1 to 1, eliminating the cases where the team would face each other, and store in a second ArrayList calling for confrontos. After defined the confrontations you shuffle them. Example:

public class CalculaConfrontos {
    public static void main(String[] args) {
        ArrayList<String> nomesTimes = new ArrayList<String>();
        nomesTimes.add("a");
        nomesTimes.add("b");
        nomesTimes.add("c");
        nomesTimes.add("d");
        ArrayList<String> confrontos = new ArrayList<String>();
        for(String t1: nomesTimes) {
            for(String t2: nomesTimes) {
                if(t1 == t2) continue;
                confrontos.add("[" + t1 + "," + t2 + "]");
            }
        }
        Collections.shuffle(confrontos);
        for(String c: confrontos) {
            System.out.println(c);
        }
    }
}

Upshot:

[a,c]
[b,c]
[c,a]
[c,b]
[a,d]
[b,d]
[d,c]
[d,]
[d,b]
[c,d]
[a,b]
[b,a]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.