-1

我有一组关于白天忙碌时间的数据,我想通过可能从一天中减去这些时间段来以某种方式实际预测空闲时间。

我想知道这样做的最佳方法/算法是什么。

[ '20:30 to 21:30',
  '11:00 to 12:00',
  '07:30 to 08:50',
  '09:00 to 20:00' ]

我现在正在考虑的是制作一个包含一天中 24 个区块的数组,最初是免费的 [1-2, 2-3, 3-4, 4-5 ..etc] 并以某种方式处理开始时间并扣除它从那个地方前。1.30 到 2.00 会将 1 的空闲块从 1-2 变为 1-1.30。这是开始的事情,但不确定它最终是否会起作用

4

2 回答 2

1

我有一个类似的问题,我有一个人的繁忙时段,并且想找到那个人可用的时段(“空闲”)。这是我编码的,希望它可以帮助某人:

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;
于 2016-04-20T12:01:11.683 回答
0

我要做的是将忙碌时间和工作时间之间的边界存储在包含实际边界(当然还有初始条件)的 Date 对象数组中。要解析您当前的日期数据,您可能需要查看为什么 Date.parse 给出不正确的结果?.

然后,要确定某个插槽是空闲还是忙碌,只需对边界数组进行二进制搜索,并根据搜索返回的位置的奇偶性来决定。

于 2013-10-06T22:13:28.827 回答