Because of this question I had to find interval intersection, but I feel my implementation is not so nice as it can be (can be? I’m sure it can…).
So I have two intervals [f1, t1]
and [f2, t2]
and I’m looking for intersection.
My code is:
private static int[] intersect(int f1, int t1, int f2, int t2) {
if ( isBetween(f1, f2, t2) ) {
return new int[] { f1, Math.min(t1, t2) };
} else if ( isBetween(f2, f1, t1) ) {
return new int[] { f2, Math.min(t1, t2) };
} else {
return null;
}
}
private static boolean isBetween(int n, int f, int t) {
return f <= n && n <= t;
}