Intersections.java



/***********************************************************
  * Donna Gabai, dgabai, P01B
  * fall10 exam 2
  * 
  * Client for Range2D object for 2-dimensional intervals.
  * All intervals are open and are in the range (0, 1).
  * 
  * Dependencies: StdIn, StdOut, StdDraw, Range1D, Range2D, Queue
  * *******************************************************/
public class Intersections {
  
  public static void main(String[] args) {
    // read in range pairs from standard input
    // assumes good data in appropriate order and quantity
    // keep count
    int count = 0;
    
    // Queue to hold them
    Queue<Range2D> ranges = new Queue<Range2D>();
    
    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);
      
      // make 2D range
      Range2D r2d = new Range2D(r1, r2);
      // output: Draw it
      r2d.draw();
      
      // count it and store it
      count++;
      ranges.enqueue(r2d);
    }
    
    // count intersections, print each if fewer than 70 ranges
    int iCount = 0;
    for (Range2D r1 : ranges) {
      for (Range2D r2 : ranges) {
        // don't intersect itself, check the reference
        if (r1 != r2) {
          if (r1.intersects(r2)) {
            iCount++;
            if (count < 70)
              StdOut.println(r1 + " intersects " + r2);
          }
        }
      }
    }
    
      // output
      StdOut.println(iCount/2 + " intersections");
  }
}