Created
March 29, 2022 15:44
-
-
Save pbrandiezs/44623d065f321ce4f6b51dc75823a09e to your computer and use it in GitHub Desktop.
Find largest gap in a list of appointments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ArrayChallenge(strArr) { | |
// code goes here | |
let appointmentArray = []; | |
let isStartPM = Boolean; | |
let isEndPM = Boolean; | |
let appointmentArrayMinutes = []; | |
let largestGapMinutes = 0; // Initialize to 0 so overlapping appointments will 0 minutes gap. | |
let start; | |
let end; | |
let startMinutes; | |
let endMinutes; | |
let gapStartMinutes; | |
let gapEndMinutes; | |
let gapSizeMinutes; | |
let largestGapHoursOnly; | |
let largestGapMinutesRemainder; | |
let largestGapHHMM; | |
// Generate an appointment array using minutes past midnight | |
for(let i = 0;i < strArr.length; i++) { | |
appointmentArray[i] = strArr[i].split('-'); | |
// Build array in minutes past midnight | |
isStartPM = false; | |
isEndPM = false; | |
start = appointmentArray[i][0]; | |
end = appointmentArray[i][1]; | |
startMinutes = parseInt(start.slice(0,2)) * 60 + parseInt(start.slice(3,5)); | |
endMinutes = parseInt(end.slice(0,2)) * 60 + parseInt(end.slice(3,5)); | |
if (start.slice(5,7) == "PM") { | |
isStartPM = true; | |
}; | |
if (end.slice(5,7) == "PM") { | |
isEndPM = true; | |
}; | |
// if PM add 12 hours | |
if ((parseInt(start.slice(0,2)) < 12 ) && isStartPM) { | |
startMinutes = startMinutes + 12 * 60; | |
} | |
if ((parseInt(end.slice(0,2)) < 12 ) && isEndPM) { | |
endMinutes = endMinutes + 12 * 60; | |
} | |
// build the array | |
appointmentArrayMinutes.push([startMinutes,endMinutes]); | |
} | |
// Sort the array | |
appointmentArrayMinutes.sort(); | |
// Loop to find the largest gap in minutes | |
for(let i = 0; i < (appointmentArrayMinutes.length -1) ; i++) { | |
gapStartMinutes = appointmentArrayMinutes[i][1]; | |
gapEndMinutes = appointmentArrayMinutes[i + 1][0]; | |
gapSizeMinutes = gapEndMinutes - gapStartMinutes; | |
if (gapSizeMinutes > largestGapMinutes) { | |
largestGapMinutes = gapSizeMinutes; | |
} | |
} | |
// Return the largest gap in HH:MM format | |
largestGapHoursOnly = parseInt(largestGapMinutes / 60); | |
largestGapMinutesRemainder = largestGapMinutes % 60; | |
largestGapHHMM = largestGapHoursOnly.toString().padStart(2,'0') + ":" + largestGapMinutesRemainder.toString().padStart(2,'0'); | |
return largestGapHHMM; | |
} | |
// keep this function call here | |
console.log(ArrayChallenge(readline())); | |
// ["12:15PM-02:00PM","09:00AM-10:00AM","10:30AM-12:00PM"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment