返回

Timefold 中的课程安排连续空白限制策略

java

如何限制 Timefold 中课程安排中的连续空白?

引言

在教育环境中,时间表管理是一个复杂的过程,需要考虑多种约束。其中一项关键约束是确保一天内课程安排的连续性,避免课程之间出现较长时间的空白。本文将探讨如何利用 Timefold 的 Timetable Constraint Solver 来实现此约束。

Timefold 中的连续课程限制

Timefold 提供了一个名为 tooMuchGap 的内置约束,它可以防止同一学生组在同一天课程之间出现超过指定时长的空白。此约束使用以下伪代码定义:

foreach pair of different lessons
  with the same student group
  in the same day
  join by start/end times (less than)
  if gap > specified duration
    penalize

限制应用

问题

我们希望对大学一天的课程安排进行限制,确保课程之间的空白时间不超过 2 小时。假设这一天有 7 个时段(8AM - 10AM、10AM - 12AM、...、8PM-10PM)和 4 节不同的课程需要安排。

代码实现

Constraint tooMuchGap(ConstraintFactory constraintFactory){
    // 学生在同一天的课程之间有 4 小时的空档
    //todo 解决这个问题-> 我们接收到的对不是连续的
    return constraintFactory
            //select each 2 pair of different lessons
            .forEach(Lesson.class)
            .join(Lesson.class,
                    //with the same student group
                    Joiners.equal(Lesson::getStudentGroup),
                    //in the same day
                    Joiners.equal((lesson) -> lesson.getTimeslot().getDayOfWeek()),
                    Joiners.lessThan((lesson -> lesson.getTimeslot().getId())))
            .filter((lesson1, lesson2) -> {
                
                Duration between = Duration.between(lesson1.getTimeslot().getEndTime(),
                        lesson2.getTimeslot().getStartTime());
                return !between.isNegative() && between.compareTo(Duration.ofHours(3)) > 0;
            })
            .penalize(HardSoftScore.ONE_SOFT)
            //.justifyWith()
            .asConstraint("Too much gap between the courses");
}

测试验证

@Test
void tooMuchGap(){
    StudentGroup studentGroup = new StudentGroup(1L,"Group1");
    Lesson firstTuesdayLesson = new Lesson(1, "subject1", new Teacher(1L, "Teacher2"), studentGroup, TIMESLOT2, ROOM1);
    Lesson secondTuesdayLesson = new Lesson(2, "subject2", new Teacher(2L, "Teacher1"), studentGroup, TIMESLOT3, ROOM1);
    Lesson thirdTuesdayLesson = new Lesson(3, "subject3", new Teacher(3L, "Teacher3"), studentGroup, TIMESLOT6, ROOM1);
    Lesson fourthTuesdayLesson = new Lesson(4, "subject4", new Teacher(4L, "Teacher3"), studentGroup, TIMESLOT7, ROOM1);
    constraintVerifier.verifyThat(TimetableConstraintProvider::tooMuchGap)
            .given(firstTuesdayLesson, secondTuesdayLesson, thirdTuesdayLesson, fourthTuesdayLesson)
            .penalizesBy(1);
}

此测试验证了 tooMuchGap 约束的行为,并确保在课程之间存在超过 2 小时空白时会对其进行处罚。

结论

Timefold 的 tooMuchGap 约束提供了对课程安排连续性的有价值限制。通过应用此约束,我们可以确保一天内的课程安排高效且有效,同时减少学生之间的空白时间。

常见问题解答

1. tooMuchGap 约束是否适用于多天?

否,tooMuchGap 约束仅适用于同一天内的课程。如果您需要限制多天的课程空白,则需要创建自定义约束。

2. 如何更改空白时长的限制?

可以通过修改 tooMuchGap 约束中的持续时间阈值来更改空白时长的限制。

3. tooMuchGap 约束是否考虑课程之间的距离?

否,tooMuchGap 约束不考虑课程之间的距离。如果您需要考虑课程之间的距离,则需要创建自定义约束。

4. tooMuchGap 约束是否适用于特定教师或房间?

否,tooMuchGap 约束不考虑特定教师或房间。如果您需要针对特定教师或房间应用约束,则需要创建自定义约束。

5. 如何禁用 tooMuchGap 约束?

您可以通过将约束的权重设置为 0 来禁用 tooMuchGap 约束。