Neat interval intersection

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;
}

don’t know java so here is the pseudo code :

int[] intersect(int f1, int t1, int f2, int t2){
	int s = max(f1,f2);
	int e = min(t1,t2);
	if(s > e)
		return NULL;
	else
		return {s,e};
}
2 Likes

Perfect :wink: That’s what I was looking for and it can be derived from my code, so I can understand well how it works and I’ll never forget…

1 Like