java - 找到列表中最接近的数字

标签 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));

Classroom 类是基本类,构造函数为 (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));
        }
    }

最佳答案

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

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

关于java - 找到列表中最接近的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41606189/

相关文章:

java - 类加载器 : Delegation Hierarchy Algorithm

java - 使用 Intent 打开 Waze GPS 导航或谷歌地图

Java 如何正确返回 Int 值?

arrays - 仅使用 3 个元素形成数组的方法有多少?

c - 读取三个引脚值

arrays - 对于每个元素,计算有多少给定子数组包含它

c++ - c++ - 如何在c++中按降序对基于第二个元素的对列表进行排序

python - 如何使用 Python 列表?

python - 如何从python中的键值对中搜索键

java - MySQL : EOFException: Can not read response from server. 预计读取 4 个字节,在连接意外丢失之前读取了 0 个字节