找到最近的列表号

时间:2017-01-12 06:08:06

标签: java algorithm list

我有一个教室列表和一个学生组列表。每个教室只能容纳x个学生。我想为每组学生找到最好的课堂。

我有以下示例。

List<Classroom> classRooms = new ArrayList<>();

classRooms .add(new Classroom("Lecture Room 1", 40));  
classRooms .add(new Classroom("Lecture Room 2", 32));
classRooms .add(new Classroom("Lecture Room 3", 80));
classRooms .add(new Classroom("Lecture Room 4", 50));
classRooms .add(new Classroom("Lecture Room 5", 26));

课堂课是基本的,具有(classroomname,maxCapicity)的构造函数 然后我有一个学生团体列表

List<StudentGroup> studentGroups= new ArrayList<>();

studentGroups.add(new StudentGroup("Group 1", 70));  
studentGroups.add(new StudentGroup("Group  2", 40));
studentGroups .add(new StudentGroup("Group  3", 10));
studentGroups.add(new StudentGroup("Group  4", 45));

如果一个小组被分配到教室,那么教室就不再可用了。构建的学生组看起来类似于教室(groupname,totalStudents)

我查看了这个Most efficient way to find the nearest number in a list,但我不想使用整数列表(教室大小),然后每次从列表中删除。有替代品吗?

提前致谢。

编辑我试过这个。但不要以为这会给出最好的结果

Collections.sort(courseList, (a, b) ->         a.getStudentCount().compareTo(b.getStudentCount()));
     Collections.sort(classList, (a, b) -> a.getMaxStudente().compareTo(b.getMaxStudente()));

    // more course than classes
    if (courseList.size() > classList.size()) {

    } else { // more clases than courses

        for (int i = 0; i < courseList.size(); i++) {
            courseList.get(i).setDedicatedKlas(classList.get(i + 1));
        }
    }

2 个答案:

答案 0 :(得分:0)

首先,您需要对教室和小组进行排序。接下来你需要把最大的团队和地方放到最大的教室。在下一次迭代中,取第二组并放置到第二个教室。 对于一些大型团体,你不能上课

classRooms = Collections.sort(classRooms , new Comparator<Classroom>() {
    public int compare(Classroom o1, Classroom o2)
    {
        return o1.getSize() < o2.getSize();
    }
});

studentGroups = Collections.sort(studentGroups, new Comparator<StudentGroup>() {
    public int compare(StudentGroup o1, StudentGroup o2)
    {
        return o1.getSize() < o2.getSize();
    }
});

int classRoomIndex = 0;
for(StudentGroup group : groups){
    while(classRoomIndex < classRooms.size()){
        Classroom classRoom = classRooms.get(classRoomIndex++);
        if(classRoom.getSize() >= group.getSize())
        {
            // place group to classroom
            break;
        }
    }
    if(classRoomIndex == classRooms.size()){
        // no classrooms for groups
        notInClass.addAll(groups.subList(groups.indexOf(group), groups.size()));
        break;
    }
    notInClass.add(group);
}

答案 1 :(得分:-2)

为什么不对两个列表进行排序,然后从顶部进行分配。