/******************************************************************************* * Donna Gabai, dgabai, P01A * * Compile: javac FindFood.java * Execute: java FindFood myLat myLon minRating < restaurantFile * Dependencies: StdIn, StdOut * * Given latitude, longitude and minimum restaurant rating * (and an input file of local restaurants) * Print out a list of acceptable nearby restaurants, starting with the closest * */ public class FindFood { // great circle distance between (x1, y1) and (x2, y2) public static double dist(double x1, double y1, double x2, double y2) { // convert to radians double xr1 = Math.toRadians(x1); double xr2 = Math.toRadians(x2); double yr1 = Math.toRadians(y1); double yr2 = Math.toRadians(y2); // use formula given double arc = Math.acos(Math.sin(xr1) * Math.sin(xr2) + Math.cos(xr1) * Math.cos(xr2) * Math.cos(yr1 - yr2)); double dist = 1.1516 * 60 * Math.toDegrees(arc); return dist; } // find closest restaurant public static int findNext(double x, double y, double[] lat, double[] lon) { int N = lat.length; double minDist = Double.POSITIVE_INFINITY; int closest = 0; for (int i = 0; i < N; i++) { double d = dist(x, y, lat[i], lon[i]); if (minDist > d) { minDist = d; closest = i; } } return closest; } // take restaurant out of consideration for findNext public static void markFound(int f, double[] lat, double[] lon) { lat[f] = Double.POSITIVE_INFINITY; lon[f] = Double.POSITIVE_INFINITY; } public static void main(String[] args) { // my location and acceptable rating double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); int rating = Integer.parseInt(args[2]); // set up arrays int N = StdIn.readInt(); String[] names = new String[N]; double[] lat = new double[N]; double[] lon = new double[N]; int[] ratings = new int[N]; // read in restaurant data for (int i = 0; i < N; i++) { names[i] = StdIn.readString(); lat[i] = StdIn.readDouble(); lon[i] = StdIn.readDouble(); ratings[i] = StdIn.readInt(); } // list acceptable restaurants, closest to farthest for (int i = 0; i < N; i++) { int next = findNext(x, y, lat, lon); if (ratings[next] >= rating) { StdOut.println(names[next] + " has a rating of " + ratings[next]); double dist = dist(x, y, lat[next], lon[next]); StdOut.printf("Distance: %.6f miles\n\n", dist); } // remove from consideration markFound(next, lat, lon); } } }