Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <math.h>
- #define BUFFER_SIZE 1024
- #define degToRad(angleInDegrees) ((angleInDegrees) * M_PI / 180.0)
- #define radToDeg(angleInRadians) ((angleInRadians) * 180.0 / M_PI)
- double getDistance(double lat1, double lon1, double lat2, double lon2)
- {
- double a = (sin((lat2 - lat1) / 2) * sin((lat2 - lat1) / 2)) + cos(lat1) * cos(lat2) * (sin((lon2 - lon1) / 2) * sin((lon2 - lon1) / 2));
- return 6371. * 2. * atan2(sqrt(a), sqrt(1 - a));
- }
- int main(int argc, char *argv[]) {
- FILE* input = fopen(argv[1], "r");
- FILE *output = fopen(argv[4], "w");
- char line[BUFFER_SIZE];
- double input_lat;
- double input_lon;
- int total = 0;
- while (fgets(line, BUFFER_SIZE, input))
- {
- char* tmp = strdup(line);
- int i = 0;
- const char* tok;
- const char* city;
- double lat;
- double lon;
- for (tok = strtok(line, ";");
- tok && *tok;
- tok = strtok(NULL, ";\n"))
- {
- switch(i) {
- case 0:
- city = tok;
- break;
- case 2:
- lat = degToRad(strtod(tok, NULL));
- break;
- case 3:
- lon = degToRad(strtod(tok, NULL));
- break;
- }
- i++;
- }
- if(strcmp(city, argv[2]) == 0) {
- input_lon = lon;
- input_lat = lat;
- }
- free(tmp);
- }
- fseek(input, 0, SEEK_SET);
- while (fgets(line, BUFFER_SIZE, input))
- {
- char* tmp = strdup(line);
- int i = 0;
- const char* tok;
- const char* city;
- int population;
- double lat;
- double lon;
- for (tok = strtok(line, ";");
- tok && *tok;
- tok = strtok(NULL, ";\n"))
- {
- switch(i) {
- case 0:
- city = tok;
- break;
- case 1:
- population = strtol(tok, NULL, 10);
- break;
- case 2:
- lat = degToRad(strtod(tok, NULL));
- break;
- case 3:
- lon = degToRad(strtod(tok, NULL));
- break;
- }
- i++;
- }
- double distance = getDistance(input_lat, input_lon, lat, lon);
- if(distance <= strtod(argv[3], NULL)) {
- fprintf(output, "%s %d %.2f km\n", city, population, distance);
- total += population;
- }
- free(tmp);
- }
- printf("total population: %d", total);
- fclose(input);
- fclose(output);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement