Home > Mobile >  Kotlin: how to check if 2 date ranges are overlapping?
Kotlin: how to check if 2 date ranges are overlapping?

Time:06-18

my current solution is like this:

(A.startAt in B.startAt..B.endAt) || 
    (A.endAt in B.startAt..B.endAt) || 
    (A.startAt <= B.startAt && A.endAt >= B.endAt)

if there is more idiomatic or performant check, please help me.

CodePudding user response:

How about max(A.startAt,B.startAt)<=min(A.endAt,B.endAt)

CodePudding user response:

The most elegant (in my subjective opinion) is probably

val overlap = a.intersect(b).isNotEmpty()

Or you could do

a.any { b.contains(it) }
// or a.any(b::contains)

which should avoid creating a new collection (which intersect does) - I feel like it's less immediately obvious what it's doing though, the first one reads better to me.


You could manually work out if the start or end of one range is between the start and end of the other, which is probably the "most efficient" way - that can be a little tricky though because you can have descending ranges, which aren't IntRanges, they're just IntProgressions (which an IntRange is a subclass of). So you'd have to do this kind of thing:

fun overlap(a: IntProgression, b: IntProgression): Boolean {
    val max = maxOf(a.first, a.last)
    val min = minOf(a.first, a.last)
    return (b.first >= min && b.first <= max) || (b.last >= min && b.last <= max)
}

and I mean, is it really worth it? (Maybe it is! But you should benchmark it if so, because you're adding complexity and there should be a concrete benefit to that tradeoff)

  • Related