在两个ArrayLists之间平均配对元素

时间:2017-10-20 15:46:50

标签: java arraylist

我的学校作业如下: 写一个获取学生和评分者名单的方法 作为参数并返回单个ArrayList,其中每个元素的格式为“studentName,graderName”。 学生应该在评分者中尽可能均匀地分开。例如,您可以将7名学生分配给一名分级员,将6名学生分配给另一名分级员,而不是8名学生分配给一个分级员,将5名学生分配给另

这就是我现在所拥有的。

    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;
}

2 个答案:

答案 0 :(得分:0)

这是你应该怎么做的:

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;
    }

答案 1 :(得分:0)

假设您有8名学生和3名教师,您只需循环浏览学生名单

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

开始学习实现接口,而不是实现到实现。 这里List将是接口,ArrayList将是你的实现。 这样你api更具适应性

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;
    }