Skip to content

Instantly share code, notes, and snippets.

@trendsetter37
Created October 19, 2014 13:08
Show Gist options
  • Select an option

  • Save trendsetter37/9c51ab0b49f01d2f89ff to your computer and use it in GitHub Desktop.

Select an option

Save trendsetter37/9c51ab0b49f01d2f89ff to your computer and use it in GitHub Desktop.
Codeeval Challenge Delta Time
/* https://www.codeeval.com/open_challenges/166/ */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1024
int time_difference(char* time1, char* time2);
void seconds_to_time(int seconds);
int main(int argc, char** argv)
{
if (argc < 2)
{
printf("You need to provide an input file");
return 1;
}
FILE *f = fopen(argv[1], "r");
char *line = malloc(MAX * sizeof(char));
while (fgets(line, MAX, f)){
if (line[0] == '\n'){ //skip empty lines
continue;
}
char* first_part = strtok(line, " ");
char* second_part = strtok(NULL, " ");
int tdiff = time_difference(first_part, second_part); // This is where the issue lies!
seconds_to_time(tdiff);
}
free(line);
return 0;
}
int time_difference(char* time1, char* time2)
{
char str[9];
char str1[9];
strncpy(str, time1, 9);
strncpy(str1, time2, 9);
int t1 = (atoi(strtok(str, ":")) * 3600) + (atoi(strtok(NULL, ":")) * 60) + atoi(strtok(NULL, ":"));
int t2 = (atoi(strtok(str1, ":")) * 3600) + (atoi(strtok(NULL, ":")) * 60) + atoi(strtok(NULL, ":"));
return abs(t1 - t2);
}
void seconds_to_time(int seconds) // will receive input from time_difference
{
int hours = seconds / 3600;
int minutes = seconds % 3600 / 60;
int secs = seconds - (hours * 3600) - (minutes * 60);
printf("%02d:%02d:%02d\n", hours, minutes, secs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment