Search code examples
javaarraylistround-robin

How can I "Round-Robin" 2 ArrayLists?


I have an assignment for school where I need to make a programme that automatically makes couples for the lessons at school. In this case there are 6 lessons and each lesson you partner with a different person. So in week 1 person a partnered with person b and the following weeks he can't partner with person a.

I have written some code that splits the class in 2, but I have no idea on how I could change the couples every week.

Here is the code I already have (sorry it isn't in english):

public void maakKoppels() {
    if (leerlingenLijst.size() % 2 == 1) {
        // if you have an odd number of students it adds the "Bye" student
        leerlingenLijst.add(new Leerling("Bye"));
    }

    for (int i = 1; i <= 6; i++) {
        //its needed for 6 lessons so it does it 6 times
        maakKoppels(i, leerlingenLijst);
    }
}

public void maakKoppels(int weekNum, ArrayList<Leerling> leerlingenLijst) {
    int midden = leerlingenLijst.size() / 2; //split the arraylist in 2

    ArrayList lijst1 = new ArrayList();
    for (int j = 0; j < midden; j++) {
        lijst1.add(leerlingenLijst.get(j));
    }

    ArrayList lijst2 = new ArrayList();
    for (int j = leerlingenLijst.size() - 1; j >= midden; j--) {
        lijst2.add(leerlingenLijst.get(j));
    }
    // here it fills the lessons with the 2 lists. weekNum is the lesson
    // number and the name on lijst1 at index 0 couples with the name on
    // lijst2 at index zero
    practica.add(new Practicum(weekNum, lijst1, lijst2));
}

Solution

  • One way to solve is as below...

    1. Split the whole class into two arraylists. L1 & L2
    2. create a variable offset = 0
    3. First week assign L1[0] & L2[0+offset] as one couple, L1[1] & L2[1+offset] as another couple and so on.
    4. Second week set offset = 1
    5. assign L1[0] & L2[0+offset] as one couple but this time, you will actually be assigning L1[0] and L2[1] as a couple because of increased offset value. 6.To ensure that you don't go beyond length of L2, use (0+offset)%L2.length()

    This will ensure you have different couple everyweek.