Created
October 5, 2017 23:01
-
-
Save fpopic/c378f233d01a0c608fa53fe4142998cd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <cstdio> | |
| #include <utility> | |
| #include <cmath> | |
| #include <string> | |
| #include <vector> | |
| #include <algorithm> | |
| using namespace std; | |
| struct TrackingEvent { | |
| string uuid; | |
| double lat; | |
| double lon; | |
| TrackingEvent(string uuid, double lat, double lon) : uuid(std::move(uuid)), lat(lat), lon(lon) {} | |
| }; | |
| struct Airport { | |
| string iata_code; | |
| double lat; | |
| double lon; | |
| Airport(string iata_code, double lat, double lon) : iata_code(std::move(iata_code)), lat(lat), lon(lon) {} | |
| }; | |
| const double PI_DIV_180 = M_PI / 180.0; | |
| inline double to_radians(const double& degree) { return degree * PI_DIV_180; } | |
| double haversine(double lat1, double lon1, double lat2, double lon2) { | |
| double phi1 = to_radians(lat1); | |
| double phi2 = to_radians(lat2); | |
| double delta_phi = to_radians(lat2 - lat1); | |
| double delta_lambda = to_radians(lon2 - lon1); | |
| double sinLat2 = sin(delta_phi / 2); | |
| double sinLon2 = sin(delta_lambda / 2); | |
| double a = sinLat2 * sinLat2 + cos(phi1) * cos(phi2) * sinLon2 * sinLon2; | |
| double c = 2 * atan2(sqrt(a), sqrt(1 - a)); | |
| return 6371e3 * c; // distance in meters | |
| } | |
| int main() { | |
| string iata_code, uuid; | |
| double lat, lon; | |
| // airports | |
| FILE* airports_file = fopen("data/airports.csv", "r"); | |
| vector<Airport> airports; | |
| fscanf(airports_file, "%s", new string); // header | |
| while (fscanf(airports_file, "%s,%lf,%lf", iata_code, &lat, &lon) == 3) { | |
| airports.push_back(Airport(iata_code, lat, lon)); | |
| } | |
| fclose(airports_file); | |
| // events | |
| FILE* events_file = fopen("data/events.csv", "r"); | |
| vector<TrackingEvent> events; | |
| fscanf(events_file, "%s", new string); // header | |
| while (fscanf(airports_file, "%s,%lf,%lf", uuid, &lat, &lon) == 3) { | |
| events.push_back(TrackingEvent(uuid, lat, lon)); | |
| } | |
| fclose(events_file); | |
| // match | |
| FILE* out_file = fopen("data/out.csv", "w+"); | |
| for (const auto& event:events) { | |
| const auto& nearestAirport = std::min_element( | |
| airports.begin(), | |
| airports.end(), | |
| [](const Airport& a1, const Airport& a2) { | |
| return haversine(a1.lat, a1.lon, event.lat, event.lon) < | |
| haversine(a2.lat, a2.lon, event.lat, event.lon); | |
| } | |
| ); | |
| fprintf(out_file, "%s,%s\n", event.uuid, nearestAirport->iata_code); | |
| } | |
| fclose(out_file); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment