计算时间范围与时间范围的重叠

时间:2019-11-06 17:48:38

标签: javascript node.js momentjs

我尝试计算给定时间范围和时间范围数组之间的重叠量(以分钟为单位)。

首先,我按开始时间对范围进行排序,如果它们与范围不重叠,则对其进行过滤。

const range = ["2019-11-06 08:00", "2019-11-06 17:00"]; // 9h
const ranges = [
  ["2019-11-06 00:00", "2019-11-06 10:00"],
  ["2019-11-06 22:00", "2019-11-06 24:00"],
  ["2019-11-06 09:00", "2019-11-06 12:00"]
]

function calculateOvelappings(range, ranges) {
  const start = moment(range[0])
  const end = moment(range[1])
  let overlaps = 0
  // order ranges by start time
  ranges = ranges.sort((a, b) => moment(a[0]).unix() - moment(b[0]).unix())
  for(let i = 0; i < ranges.length; i++) {
    const rangeStart = moment(ranges[i][0])
    const rangeEnd = moment(ranges[i][1])
    if (rangeEnd.isBefore(start) || rangeStart.isAfter(end)) {
      continue;
    }
    
  }
  return overlaps
}


console.log(calculateOvelappings(range, ranges))
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>

编辑

重叠的正确答案是4个小时。输入范围从08:00开始,与范围1(来自数组)的交点直到10:00(2小时)。范围2无关紧要。范围3与输入范围09:00至12:00重叠,但是已经从范围1计算了09:00至10:00。因此2 +(3-1)= 4小时。

是否有一个优雅的算法来计算? 任何帮助,伪代码甚至是理论上的帮助都将不胜感激。

这是一个JsBin:https://jsbin.com/noyuhekura/1/edit?js,console

1 个答案:

答案 0 :(得分:0)

const range = ["2019-11-06 08:00", "2019-11-06 17:00"]; // 9h
const ranges = [
  ["2019-11-06 00:00", "2019-11-06 10:00"],
  ["2019-11-06 22:00", "2019-11-06 24:00"],
  ["2019-11-06 09:00", "2019-11-06 12:00"]
]

function calculateOvelappings(range, ranges) {
  const start = moment(range[0])
  const end = moment(range[1])
  let overlaps = 0
  // order ranges by start time
  ranges = ranges.sort((a, b) => moment(a[0]).unix() - moment(b[0]).unix())
  for(let i = 0; i < ranges.length; i++) {
    const rangeStart = moment(ranges[i][0])
    const rangeEnd = moment(ranges[i][1])
    if (rangeEnd.isBefore(start) || rangeStart.isAfter(end)) {
      continue;
    }
    overlaps += rangeEnd - rangeStart // Updated
  }
  return overlaps
}


console.log(calculateOvelappings(range, ranges))