Join two Arraylist

1

I made a ArrayList ( nomeTimes ) that receives a number of team names according to for 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 merge the data from the two Arraylists into a third one.

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

How to join the two in a third?

    
asked by anonymous 03.11.2014 / 18:18

1 answer

5

I thought the following way: Instead of having two ArrayList s you only need one, which has the teams name. Then you make a permutation 1 to 1, eliminating the cases in which the team would face, and store in a second ArrayList called confrontos . Once defined the clashes 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);
        }
    }
}

Result:

  

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

    
03.11.2014 / 18:45