Last active
December 29, 2019 17:22
-
-
Save ImaginativeShohag/3f05893f8ae88454690c629e1a3c39e4 to your computer and use it in GitHub Desktop.
Check if an event overlaps with other events. https://pl.kotl.in/3G0a6x1fz
This file contains hidden or 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
private val appointmentEventList = mutableListOf<AppointmentEvent>() | |
/** | |
* Note: Time should be 24 hours. | |
**/ | |
fun main() { | |
appointmentEventList.add(AppointmentEvent(230, 300)) // 02:30 - 03:00 | |
appointmentEventList.add(AppointmentEvent(600, 700)) // 06:00 - 07:00 | |
appointmentEventList.add(AppointmentEvent(700, 800)) // 07:00 - 08:00 | |
appointmentEventList.add(AppointmentEvent(1000, 1030)) // 10:00 - 10:30 | |
appointmentEventList.add(AppointmentEvent(1100, 1200)) // 11:00 - 12:00 | |
println("AppointmentTime(3:00, 4:00): ${isValidTime(AppointmentEvent(300, 400))}") | |
println("AppointmentTime(4:00, 5:00): ${isValidTime(AppointmentEvent(400, 500))}") | |
println("AppointmentTime(5:00, 6:00): ${isValidTime(AppointmentEvent(500, 600))}") | |
println("AppointmentTime(8:00, 10:00): ${isValidTime(AppointmentEvent(800, 1000))}") | |
println("AppointmentTime(2:00, 4:00): ${isValidTime(AppointmentEvent(200, 400))}") | |
println("AppointmentTime(5:00, 7:00): ${isValidTime(AppointmentEvent(500, 700))}") | |
println("AppointmentTime(1:00, 2:00): ${isValidTime(AppointmentEvent(100, 200))}") | |
println("AppointmentTime(11:00, 12:00): ${isValidTime(AppointmentEvent(1100, 1200))}") | |
println("AppointmentTime(12:00, 13:00): ${isValidTime(AppointmentEvent(1200, 1300))}") | |
} | |
private fun isValidTime(targetEvent: AppointmentEvent): Boolean { | |
// check if there is any event! | |
if (appointmentEventList.isEmpty()) { | |
return true | |
} | |
// Sort by end time | |
appointmentEventList.sortBy { | |
it.endTime | |
} | |
appointmentEventList.forEachIndexed { index, appointmentEvent -> | |
// find the immediate next event of the target event | |
if (appointmentEvent.startTime >= targetEvent.endTime) { | |
// is it first? | |
return if (index == 0) { | |
true | |
} | |
// if not first | |
else { | |
// get previous one | |
val previousAppointmentEvent = appointmentEventList[index - 1] | |
// check end time | |
previousAppointmentEvent.endTime <= targetEvent.startTime | |
} | |
} | |
} | |
// Check the end time of the last event | |
if (appointmentEventList[appointmentEventList.size - 1].endTime <= targetEvent.startTime) { | |
return true | |
} | |
return false | |
} | |
data class AppointmentEvent( | |
val startTime: Int, | |
val endTime: Int | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment