|
Bill Teter email: william.teter@plattsburgh.edu |
|
|
Lab 7--Comparators and sorting arrays. The problem: Points in the Cartesian plane are specified as a pair of doubles. For example, (2.1, 3.0). There are a variety of orderings that can be defined for these pairs. You will create two classes that implement the Comparator interface that implement two of these ordering specifications. Then you will a write test program that reads a file of pairs and stores the pairs in one ArrayList. Then use the sort routine in the Array class to sort the pairs using the two ordering listed below. Your test program will print the sorted pairs in each ordering. The classes you will write are specified below. Pair class Two fields of type double ByX class implements Comparator<Pair> The pair (a,b) is less than (c,d) if a<c or if a=c and b<d. ByY class implements Comparator<Pair> Test class To process the file you will need a BufferedReader and a FileReader objects. After you have read a line that string will have to be split in two using the split method in the String class. A regular expression that works in this case is the string of one blank: " ". Now you should have an array of strings of length 2. Use the Double.parseDouble() static method to turn these strings into doubles so that you can create a Pair. Look in the Arrays class and find a sort() method that will sort an array of a parameterized type T using a specified comparator<T>. Look in the ArrayList class and find a method called toArray() that returns an array of a parameterized type T. Your test program will convert the ArrayList of Pairs into an array of Pairs, sort it using a ByX comparator. Your program should now save the smallest and largest x values that occur among all pairs. Also, print the resulting list of pairs. Now sort the array again using a ByY comparator. Again remember the smallest and largest y values among all pairs, print the Pairs in order ByY. Print the pair that is the lower left corner and the pair that is the upper right corner of the smallest rectangle containing all the pairs. This is too much code for one main method. You can modularize the
tasks many ways. You can be creative and find your own design. Or, you can
follow my suggested design. I suggest you break down the problem into
steps each with its own method: sort the array by X coordinate, print results and set the global fields smallestX and largestX sort the array by Y coordinate, print results and set the global fields smallestY and largestY There is a data file for this project in: /home/teterwa/public/csc223/lab7 |