Tuesday, January 17, 2012

Given 2 time intervals, how do you find out if there is overlap between them?

Given 2 time intervals, how do you find out if there is overlap between them?

Say you have 2 time intervals ti1 = [t1, t2] and ti2 = [t3, t4]. You can say that there is overlap between ti1and ti2  if and only if  ( (t1 < t4) AND (t2 > t3) ).


Time interval overlap

Here is my Java code snippet.
[Java code snipet] Time interval


package ric.interviewqa4java;
import java.util.Date;

@SuppressWarnings("deprecation")
/** © 2012 interviewqa4java.blogspot.com */
public class TimeIntervalProblem {
   
    public static void main(String[] args) {
       
        TimeIntervalProblem.Interval interval1=null, interval2=null;
        interval1 = new TimeIntervalProblem().new Interval(new Date("2010/1/1"), new Date("2013/1/1"));
        interval2 = new TimeIntervalProblem().new Interval(new Date("2012/1/1"), new Date("2014/1/1"));
       
        boolean result =isThereOverlap(interval1, interval2);
        System.out.println("Is there overlap between "+ interval1 + " and "+ interval2 + "? " + result);       
    }
    //Solution logic here
    private static boolean isThereOverlap(Interval t1, Interval t2) {
        return t1.begin.before(t2.end) && t1.end.after(t2.begin);
    }

     private class Interval{
        private Date begin;
        private Date end;
        private Interval(Date begin, Date end) { this.begin = begin; this.end = end;}
        @Override
        public String toString() {
            return "[" + toString(begin) + ", " + toString(end) + "]";
        }
        private String toString(Date Date) {
            return ""+(1900+Date.getYear())+"-"+(1+Date.getMonth())+"-"+Date.getDate();
        }       
    }
}

No comments:

Post a Comment

Please, before starting to comment, evaluate if what you want to write is useful, respectful and positive. A kid may read this also.

Give a good example!