Optimize scheduling comparisons by weekday

This commit is contained in:
biss committed 2026-11-30 20:40:17 +08:00
1 parent ca60ea6132
commit 31ecf090b4
1 file changed
+11 -3
@@ -134,6 +134,9 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
private readonly Dictionary<Guid, bool> groundFloorByTask = tasks.ToDictionary(task => task.Id, RequiresGroundFloor);
private readonly Dictionary<Guid, int[]> preferredDaysByTask = constraints.ToDictionary(
pair => pair.Key, pair => ParsePreferredDays(pair.Value.PreferredDayOfWeeks));
private readonly Dictionary<int, List<ScheduleEntry>> baselineByDay = baselineEntries
.GroupBy(entry => entry.DayOfWeek)
.ToDictionary(group => group.Key, group => group.ToList());
private readonly int firstActivePeriod = activePeriods.Min();
private readonly int lastActivePeriod = activePeriods.Max();
@@ -270,7 +273,7 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
foreach (var room in roomOptions)
{
var candidate = CreateEntry(demand, startWeek, day, start, room);
if (CanAdd(candidate, baselineEntries))
if (CanAdd(candidate, baselineByDay.GetValueOrDefault(day) ?? []))
candidates.Add(candidate);
}
}
@@ -352,8 +355,13 @@ public sealed class AutomaticScheduleGenerator(AppDbContext db)
IReadOnlyList<ScheduleEntry> candidates,
IReadOnlyList<ScheduleEntry> state)
{
var feasible = candidates.Where(candidate => CanAdd(candidate, state))
.OrderBy(candidate => CandidateScore(candidate, state))
// Both conflict detection and candidate scoring only depend on entries on the same day.
var stateByDay = state.GroupBy(entry => entry.DayOfWeek)
.ToDictionary(group => group.Key, group => group.ToList());
IReadOnlyList<ScheduleEntry> StateFor(ScheduleEntry candidate) =>
stateByDay.TryGetValue(candidate.DayOfWeek, out var entries) ? entries : [];
var feasible = candidates.Where(candidate => CanAdd(candidate, StateFor(candidate)))
.OrderBy(candidate => CandidateScore(candidate, StateFor(candidate)))
.ToList();
if (feasible.Count == 0) return null;
var sampleSize = Math.Clamp((int)Math.Ceiling(feasible.Count / 4d), 1, 8);