Skip to content

Instantly share code, notes, and snippets.

@andriesfc
Created June 1, 2022 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriesfc/20412b74bad98d4cd98f5b374b25978a to your computer and use it in GitHub Desktop.
Save andriesfc/20412b74bad98d4cd98f5b374b25978a to your computer and use it in GitHub Desktop.
Collecting events with overlapping dates
import java.time.LocalDate
data class Event(val id: Int, val startDate: LocalDate, val endDate: LocalDate, val name: String)
fun LocalDate(string: String): LocalDate = LocalDate.parse(string)
fun Event.overlap(another: Event): Boolean {
// this:------(start)----------------(end)---------------------->
// another:-------------------(start)--------------------(end)----->
if (another.startDate >= startDate && another.endDate>= endDate) {
return true
}
// this:------(start)----------------(end)---------------------->
// another:-(start)--------------------------------------(end)----->
if (another.startDate < startDate && another.endDate >= endDate) {
return true
}
// this:------(start)----------------(end)---------------------->
// another:----------(start)----------(end)------------------------>
if (another.startDate >= startDate && another.endDate <= startDate) {
return true
}
return false
}
fun main(args: Array<String>) {
val events = listOf(
Event(1, LocalDate("2022-04-20"), LocalDate("2022-04-21"), "event-1"),
Event(2, LocalDate("2022-04-21"), LocalDate("2022-04-21"), "event-2"),
Event(3, LocalDate("2022-05-01"), LocalDate("2022-05-01"), "event-3"),
Event(4, LocalDate("2022-05-06"), LocalDate("2022-05-10"), "event-4"),
Event(5, LocalDate("2022-05-09"), LocalDate("2022-05-12"), "event-5")
).sortedBy(Event::startDate)
val overlappingEvents =
events.fold(mutableListOf<MutableList<Event>>()) { collected, event ->
if (collected.isEmpty()) {
collected += mutableListOf(event)
} else if (event.overlap(collected.last().last())) {
collected.last().add(event)
} else {
collected.add(mutableListOf(event))
}
collected
}
overlappingEvents.forEachIndexed { index, list ->
println("[${index + 1}] --------------------------------------------------")
list.forEach(::println)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment