我有一個類似的問題,我只好一個人忙插槽,想找個時間插槽,該人是可用的(「自由」)。這是我編碼,希望它可以幫助別人:
function getFreeOfDay (date, busySlots) {
function sameDateDifferentTime(date, hours, minutes) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), hours, minutes, 0, 0);
}
// Define the range for free spots
var freeSlots = date.getDay() === 0 || date.getDay() === 6 ? [] : [
{
start: sameDateDifferentTime(date, 10, 0), // 10:00 (AM)
end: sameDateDifferentTime(date, 12, 30), // 12:30 (AM)
},
{
start: sameDateDifferentTime(date, 13, 30), // 13:30 (AM)
end: sameDateDifferentTime(date, 19, 0), // 19:00 (AM)
}
];
// Go through the busy slots, to remove them from the free spots
busySlots.forEach(function (busySlot) {
freeSlots.forEach(function (freeSlot, freeSlotIndex) {
if (busySlot.end <= freeSlot.start || busySlot.start >= freeSlot.end) {
// Do nothing, the busy slot doesn't interfere with the free slot
}
else if (busySlot.start <= freeSlot.start && busySlot.end >= freeSlot.end) {
// The free slot is in the middle of the busy slot, meaning it's not possible to plan anything in there
freeSlots.splice(freeSlotIndex, 1);
}
else if (busySlot.start < freeSlot.start && busySlot.end > freeSlot.start) {
// The busy slot overlaps with the free slot, it ends after the start of the free slot
freeSlots[freeSlotIndex] = {
start: busySlot.end,
end: freeSlot.end
};
}
else if (busySlot.start < freeSlot.end && busySlot.end > freeSlot.end) {
// The busy slot overlaps with the free slot, it starts before the end of the free slot
freeSlots[freeSlotIndex] = {
start: freeSlot.start,
end: busySlot.start
};
}
else {
// Then the busy slot is in the middle of a free slot
freeSlots[freeSlotIndex] = {
start: freeSlot.start,
end: busySlot.start
};
freeSlots.splice(freeSlotIndex + 1, 0, {
start: busySlot.end,
end: freeSlot.end
});
}
});
});
// Remove empty free slots
freeSlots.forEach(function (freeSlot, freeSlotIndex) {
if (freeSlot.start >= freeSlot.end) {
freeSlots.splice(freeSlotIndex, 1);
}
});
return freeSlots;
你有什麼想法嗎? 「什麼是最好的方法/算法」---你至少有什麼工作,你認爲是「不是最好的」? – zerkms
我不確定你在問什麼。你可以創建一個不繁忙的時間模板,比如「9:00-19:00」,然後製作一個空閒時間的交集(http://en.wikipedia.org/wiki/Intersection_%28set_theory%29)忙碌的時間。在此之後,你只需要將數據轉換爲一些數字。 –
您可以將一整天(24小時)分成代表5分鐘時段的數字數組,然後對於數據中的每個字符串增加相應時段中的計數器。最後,對數組進行排序。您正在尋找最低號碼的插槽。 –