JS compares whether multiple times have intersection

background

I encountered a slightly interesting problem today. Let me record it. Of course, it is not a very complicated requirement, and the solution is very simple and rude. Of course, if you have better ideas, welcome to comment and exchange.

Suppose we have an object array, which stores time, start time and end time, similar to the following.

  var arr  = [
   {
    
    
       start:"08:00",
       end:"08:30"
     },
      {
    
    
       start:"08:30",
       end:"09:00"
     },
      {
    
    
       start:"09:00",
       end:"09:30"
     }
   ];

The length of the array is unknown, but the start time of each element is less than or equal to the end time. We need to judge whether there is an intersection of time in this array?

Let me briefly talk about my thinking, first of all, how to judge whether there is an intersection between two times, and what are the situations where there is an intersection. As shown below.
insert image description here
It probably includes these four situations. Then there are two cases where there is no intersection.
insert image description here
Therefore, we can obtain the intersection by judging that there is no intersection and negating it. The code is relatively simple to implement, so I only write a little here.
We only need to judge that the end time of the first time is less than or equal to the start time of the second time or the start time of the second time is greater than or equal to the end time of the first time.

 checkTimes() {
    
    
  //简单点,双重循环,判断每一个时间和其他任意一个时间有没有交集
    for (let i = 0; i < this.arr.length; i++) {
    
    
      let start1 = new Date("2022-05-19 " + this.arr[i].start);
      let end1 = new Date("2022-05-19 " + this.arr[i].end);
      for (let j = i+1; j < this.arr.length; j++) {
    
    
        let start2 = new Date("2022-05-19 " + this.arr[j].start);
        let end2 = new Date("2022-05-19 " + this.arr[j].end);
        //交集判断情况较多,我们采用非交集取反的方式,
        //非交集有两种情况,12AB  AB12
        //即1结束时间小于等于2开始时间或者1开始时间大于等于2结束时间
        if (!(end1 <= start2 || start1 >= end2)) {
    
    
          return false;
        }
      }
    }
    return true;
  },

have a wonderful day.

Guess you like

Origin blog.csdn.net/u012869793/article/details/126508599