Range1D.java



/***********************************************************
  * Donna Gabai, dgabai, P01B
  * fall10 exam 2
  * 
  * Range1D object for 1-dimensional intervals.
  * All intervals are open and are in the range (0, 1).
  * 
  * Dependencies: StdIn, StdOut
  * *******************************************************/

public class Range1D {
  // instance variables
  private double lo;    // low end of range
  private double hi;    // high end of range
  
  // constructor
  public Range1D(double lo, double hi) {
    this.lo = lo;
    this.hi = hi;
  }
  
  // Does this range intersect that?
  public boolean intersects(Range1D that) {
    // if hi of each is above lo of other
    if (this.lo < that.hi && that.lo < this.hi)
      return true;
    return false;
  }
  
  // Midpoint of this range
  public double mid() {
    return (lo + hi) / 2.0;
  }
  
  // Length of this range
  public double size() {
    return (hi - lo);
  }
  
  // string representation of a range
  public String toString() {
    String s = "(" + lo + ", " + hi + ")";
    return s;
  }
  
  // test main
  public static void main(String[] args) {
    // read in range pairs from standard input
    // assumes good data in appropriate order and quantity
    while(!StdIn.isEmpty()) {
      // first range
      double lo1 = StdIn.readDouble();
      double hi1 = StdIn.readDouble();
      Range1D r1 = new Range1D(lo1, hi1);
      
      // second range
      double lo2 = StdIn.readDouble();
      double hi2 = StdIn.readDouble();
      Range1D r2 = new Range1D(lo2, hi2);
      
      // output: Do they intersect?
      if (r1.intersects(r2))
        StdOut.println(r1 + " intersects " + r2);
      else
        StdOut.println(r1 + " and " + r2 + " are disjoint");
    }
  }
  
}