Counting Overlaps of Integer Ranges

后端 未结 3 1510
暗喜
暗喜 2021-02-10 03:28

I\'ve been stumped on this algorithm for quite a bit.

Say there are four ranges of integers. Each range has a Start and an End value.

Range A: 0,5
Range         


        
3条回答
  •  面向向阳花
    2021-02-10 03:47

    function checkOverlap(arr){
      var overlaps = {}, i, j;
      // match each item against all others BUT itself
      for( i=0; i < arr.length; i++ )
          for( j=0; j < arr.length; j++ )
              if( arr[i] !== arr[j] && arr[i][1] < arr[j][2] && arr[j][1] < arr[i][2] )
                overlaps[arr[i][0]] = 1;
    
      return Object.keys(overlaps);
    }
    

    Run it against an Array of ranges, for example:

    [
      ["a", 10, 12], 
      ["b", 20, 30], 
      ["c", 29, 30], 
      ["d", 15, 95], 
      ["e", 195, 196]
    ];
    

    Playgroud demo

提交回复
热议问题