2017-09-12 73 views
-3

我有一個JavaScript中的問題,我需要確定數字範圍的集合是否有重疊。 例子:如何檢查重疊的多個數字範圍injavascript

1 - 5, 4 - 6, 7 - 8 (具有重疊)

1 - 5, 6 - 8, 9 - 12 (無重疊)

在此先感謝!

+1

你嘗試過什麼嗎? – Rajesh

+0

他們總是按升序排列嗎?此外,你的輸入類型是什麼? – RomanPerekhrest

+0

我還沒有代碼..希望以任何順序.. input [type ='text'] – claire

回答

1

範圍集合必須先排序,以便起始元素總是大於(不小於)以前的起始數字。在您的情況下,它是排序的。 然後,對於每個範圍,檢查起始數字是否大於前一個結束數字。如果在所有範圍內都是如此,則它不重疊。

var ranges=[[1,5],[4,6],[7,8]]; 
ranges.sort() // sorting is done with respect to the first element in the array. 
for(var i=1;i<ranges.length;i++){ //start with the second element and compare it with the first 
    if(ranges[i][0]<=ranges[i-1][1]) 
     break; 
} 
if(i==ranges.length) 
    console.log("Non overlapping") 
else 
    console.log("overlapping") 
+0

這是什麼我需要!非常感謝你@ jedi_rockstar! – claire

+0

試試這個[[1,5],[6,10] [9,10]] ..這是不允許的.. :( – claire

+0

只是想通了!.. horray ! 'if(parseInt(ranges [i] [0])<= parseInt(ranges [i-1] [1])) – claire