简体   繁体   中英

Pair elements equally between two ArrayLists

I have a school assignment that goes like this: Write a method that takes the lists of students and graders as arguments and returns a single ArrayList where each element has the format "studentName, graderName". The students should be split as evenly as possible among the graders. For example, you may assign 7 students to one grader and 6 to another, but not 8 students to one grader and 5 to another.

This is what I have for now.

    public static ArrayList<String> assignGraders(ArrayList<String> students, ArrayList<String> graders) {
    ArrayList<String> list = new ArrayList<>();
    int average = students.size()/graders.size();
    int j = 0; //Index of grader list
    for(int i = 0; i<students.size(); i++) {
        list.add(students.get(i) + ", " + graders.get(j));
        if((i % average == 0) && (i!= 0) && (j<graders.size()-1)){
            j++;
        }
    }
    return list;
}

This is how you should do it:

public static ArrayList<String> assignGraders(List<String> students, List<String> graders) {
        ArrayList<String> list = new ArrayList<>();
        int average = students.size()/graders.size();
        int j = 0; //Index of grader list
        for(int i = 0; i<students.size(); i++) {
            list.add(students.get(i) + ", " + graders.get(j));
            j++;
            if (j == graders.size()) {
                j = 0;
            }
        }
        return list;
    }

All you need is to cycle through the list of students, assuming you have 8 students and three teachers

First student --> first teacher
Second student --> Second teacher
Third student --> Third teacher
Fourth student --> first teacher
Fifth student --> Second teacher
Sixth student --> Third teacher
Seventh student --> first teacher
Eight Student --> Second Teacher

Start learning to Implement to an Interface, rather implement to an implementation. Here List would be the interface and ArrayList would be your implementation. That way you api is more adaptable

public static ArrayList<String> assignGraders(ArrayList<String> students, ArrayList<String> graders)
    {
        int studentsSize = students.size();
        int gradersSize = graders.size();

        int studentToGrader = studentsSize / gradersSize;
        int assignedStudents = 0;

        ArrayList<String> studToGrader = new ArrayList<String>(students.size());
        while(assignedStudents < studentsSize)
        {
            int i = 0;
            while(i < studentToGrader)
            {
                studToGrader.add(students.get(assignedStudents) + "--" + graders.get(i));
                assignedStudents++;
                i++;
            }
        }
        return studToGrader;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM