import java.util.*;
/** RatNumComparator implements a compare() between two RatNum Objects
*/
class RatNumComparator implements Comparator {
// @requires r1 instanceof RatNum, r2 instanceof RatNum
// TODO: Modify this compare method so that it returns
// a negative number if r1 > r2,
// zero if r1 == r2
// a positive number if r1 < r2
// Integer.MAX_VALUE if r1.isNaN() && !r2.isNaN()
// Integer.MIN_VALUE if r2.isNaN() && !r1.isNaN()
// 0 if r1.isNaN() && r2.isNaN()
public int compare (Object r1, Object r2) {
// Your code here. Hint, if r1 = a/b and r2 = c/d,
// then r1 < r2 iff a * d < b * c.
return 0;
}
}
/** This class contains a main method which fills a List with
* randomly generated RatNum objects and then sorts them using
* RatNumComparator
*/
public class RatNumSortingTest {
// You should not need to modify this class
// at all. You only need to implement the compare method in the
// class RatNumComparator. The code below shows examples of how to
// generate random numbers and use an Iterator.
public static void main (String[] args) {
// create a big list of RatNums, but not in a sorted order
List ratnumList = new ArrayList();
// Fill the list using randomly generated RatNum Objects:
// 1. First, create a random number generator
Random generator = new Random();
// 2. Populate the list by creating random numerators and denominators
for (int i = 0; i < 10; i++) {
int randomNumer = generator.nextInt (20);
int randomDenom = generator.nextInt (5);
ratnumList.add (new RatNum (randomNumer, randomDenom));
}
// 3. Now call the Collections.sort() using our custom comparator
Collections.sort (ratnumList, new RatNumComparator());
// 4. Print out the list to see verify correctness.
System.out.println ("Contents of sorted list of RatNums:");
System.out.println ("***********************************");
for (Iterator i = ratnumList.iterator(); i.hasNext();) {
RatNum nextInList = (RatNum) i.next();
System.out.print (nextInList.unparse() + " ");
}
// extra line break to make the output look nice
System.out.println ("");
}
}