// java Purple < states48.txt // java Purple < TX.txt // cat [A-Z][A-Z].txt | java Purple import java.awt.Color; public class Purple { // given a number x between 0 and 1, convert to a shade of purple public static Color purple(double x) { int val = (int) (256 * x); return new Color(val, 0, 255 - val); } // find percentage of votes for given candidate in data file public static Color getColor(String name, String usps) { In in = new In("usatoday/" + usps + "-total.txt"); String input = in.readAll(); input = input.toLowerCase(); input = input.replaceAll(" ", ""); name = name.toLowerCase(); name = name.replaceAll("parish", ""); name = name.replaceAll("city", ""); name = name.replaceAll(" ", ""); int i0 = input.indexOf(name); int i1 = input.indexOf(",", i0 + 1); int i2 = input.indexOf(",", i1 + 1); int i3 = input.indexOf(",", i2 + 1); if (i0 == -1) { System.out.println("***name = " + name + ", usps = " + usps); return StdDraw.BLACK; } int bush = Integer.parseInt(input.substring(i1 + 1, i2)); int kerry = Integer.parseInt(input.substring(i2 + 1, i3)); return purple(1.0 * bush / (bush + kerry)); // if (bush > kerry) return StdDraw.RED; // else return StdDraw.BLUE; } public static void main(String[] args) { double ratio = 0.6; // a hack int HEIGHT = 800; int WIDTH = (int) (HEIGHT / ratio); StdDraw.setCanvasSize(WIDTH, HEIGHT); // bounding box double xmin = -124.731; double xmax = -66.980; double ymin = 24.544; double ymax = 49.384; StdDraw.setXscale(xmin, xmax); StdDraw.setYscale(ymin, ymax); // read in polygons and plot while (!StdIn.isEmpty()) { String name = StdIn.readLine(); String usps = StdIn.readLine(); int N = StdIn.readInt(); Polygon poly = new Polygon(); for (int i = 0; i < N; i++) { double x = StdIn.readDouble(); double y = StdIn.readDouble(); Point p = new Point(x, y); poly.add(p); } StdDraw.setPenColor(getColor(name, usps)); poly.fill(); StdDraw.show(20); StdIn.readLine(); // ignore StdIn.readLine(); // ignore } // state borders StdDraw.setPenRadius(0.005); StdDraw.setPenColor(StdDraw.WHITE); In sin = new In("states48.txt"); while (!sin.isEmpty()) { String name = sin.readLine(); String usps = sin.readLine(); int N = sin.readInt(); Polygon poly = new Polygon(); for (int i = 0; i < N; i++) { double x = sin.readDouble(); double y = sin.readDouble(); Point p = new Point(x, y); poly.add(p); } poly.draw(); StdDraw.show(20); sin.readLine(); // ignore sin.readLine(); // ignore } } }