[英]How to find common intervals between hours?
我有兩個帶間隔的數組:
[
[
[8:00, 11:30], // [begin,end]
[12:00, 16:00], // [begin,end]
[18:00, 21:00] // [begin,end]
],
[
[8:00, 15:30], // [begin,end]
[16:00, 17:45], // [begin,end]
[19:00, 21:30] // [begin,end]
]
]
我需要找到這些時間的共同間隔,所以它應該是:
[
[8:00, 11:30],
[12:00, 15:30],
[19:00, 21:00]
]
我將小時更改為分鍾,然后將第一個數組中的間隔與第二個數組中的間隔進行比較,但輸出不像上面顯示的那樣。
有誰知道如何解決它?
let hours = [[[8:00,11:30],[12:00,16:00],[18:00,21:00]]
[[8:00,15:30],[16:00,17:45],[19:00,21:30]]]
let commonHors=[];
for (let i=0; i<(hours||[]).length; i++){
for(let j=0; j<(hours||[])[i].length; j++){
let fromFirst = moment.duration(hours[0][j][0]).minutes() +
moment.duration(hours[0][j][0]).hours()*60;
let fromSec = moment.duration(hours[1][j][0]).minutes() +
moment.duration(hours[1][j][0]).hours()*60;
let toFirst = moment.duration(hours[0][j][1]).minutes() +
moment.duration(hours[0][j][1]).hours()*60;
let toSec = moment.duration(hours[1][j][1]).minutes() +
moment.duration(hours[0][j][1]).hours()*60;
if(fromFirst >= fromSec && toFirst <= toSec){
commonHors.push(hours[0][j][0],hours[0][j][1]);
}
else if(fromFirst <= fromSec && toFirst <= toSec){
commonHors.push(hours[1][j][0],hours[0][j][1]);
}
else if(fromFirst >= fromSec && toFirst >= toSec){
commonHors.push(hours[0][j][0],hours[1][j][1]);
}
else if(fromFirst <= fromSec && toFirst >= toSec){
commonHors.push(hours[1][j][0],hours[1][j][1]);
}
}
}
到目前為止,這不是最漂亮的解決方案,但它在輸入數據有效且已經排序的條件下工作。 我希望我理解你的問題,我的解決方案是有幫助的。 編輯:我使用字符串而不是其他時間格式 - 剛剛意識到但改變它應該不難,因為我是按數值排序的;
let intervals = [
[
['8:00', '11:30'],
['12:00', '16:00'],
['18:00', '21:00']
],
[
['8:00', '15:30'],
['16:00', '17:45'],
['19:00', '21:30']
]
];
let out = [];
while(intervals[0].length > 0) {
let laterNum = later(0, 0);
let startTime = intervals[laterNum][0][0];
let earlyNum = earlier(0, 1);
let endTime = intervals[earlyNum][0][1];
if (Number(endTime.replace(':', '')) > Number(startTime.replace(':', '')))
out.push([startTime, endTime]);
intervals[earlyNum].splice(0, 1);
}
function earlier(line, time) {
let a = intervals[0][line][time];
let b = intervals[1][line][time];
return Number(a.replace(':', '')) < Number(b.replace(':', '')) ? 0 : 1;
}
function later(line, time) {
return earlier(line, time) === 1 ? 0 : 1;
}
console.log(out);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.