The Java Program: Main.java

  1 import java.lang.Comparable;
  2 import java.util.Comparator;
  3 import java.util.TreeSet;
  4 import java.util.SortedSet;
  5 import java.util.Iterator;
  6 import java.util.Random;
  7 
  8 import static java.lang.Math.*;
  9 import static java.lang.System.out;
 10 
 11 public class Main {
 12 
 13    static class Point implements Comparable <Point> {
 14       private final double x,y;   // immutable
 15       Point (double x, double y) { this.x=x; this.y=y; }
 16       public double distance ()  { return sqrt(x*x + y*y); }
 17       public double manhattan () { return abs(x) + abs(y); }
 18       public String toString ()  { return "("+x+","+y+") d="+distance(); }
 19       public static int compare (double d1, double d2) {
 20          return new Double (d1).compareTo (new Double (d2));
 21       }
 22       public int compareTo (Point p) {
 23          return (Point.compare (distance(), p.distance()));
 24       }
 25    }
 26 
 27    // Implements the "Manhattan" metric
 28    static class PointComparator implements Comparator <Point> {
 29       public int compare (Point p, Point q) {
 30          return Point.compare (p.manhattan(), q.manhattan());
 31       }
 32    }
 33 
 34    public static void main (String[] args) {
 35       final Random rng = new Random();
 36 
 37       /* Keep random numbers in order (distance from origin), and print  */
 38       SortedSet <Point> set = new TreeSet <Point> ();
 39 
 40       for (int i=0; i<12; i++) {
 41          set.add (new Point(100*rng.nextDouble(), 100*rng.nextDouble()));
 42       }
 43 
 44       for (Point p: set) out.println (p);
 45       out.println ();
 46 
 47       /* Keep random numbers in order (Manhattan metric), and print  */
 48       set = new TreeSet <Point> (new PointComparator());
 49       for (int i=0; i<12; i++) {
 50          set.add (new Point(100*rng.nextDouble(), 100*rng.nextDouble()));
 51       }
 52 
 53       for (Point p: set) out.println (p);
 54    }
 55 }