Created
July 13, 2016 02:49
-
-
Save rbreslow/51c37925e8ae2b72c19fba01dcd9fd18 to your computer and use it in GitHub Desktop.
This file contains 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
typedef struct | |
{ | |
char* singular; | |
char* plural; | |
int duration; | |
} conversion_t; | |
const conversion_t CONVERSIONS[7] = { | |
{"year", "years", 31536000}, | |
{"month", "months", 2628000}, | |
{"week", "weeks", 604800}, | |
{"day", "days", 86400}, | |
{"hour", "hours", 3600}, | |
{"minute", "minutes", 60}, | |
{"second", "seconds", 1} | |
}; | |
const size_t TOTAL_CONVERSIONS = sizeof(CONVERSIONS) / sizeof(conversion_t); | |
char* secondsToStringTime(int seconds) | |
{ | |
int valid_results = 0; | |
char* result[TOTAL_CONVERSIONS]; | |
for(int i = 0; i < TOTAL_CONVERSIONS; i++) | |
{ | |
char* singular = CONVERSIONS[i].singular; | |
char* plural = CONVERSIONS[i].plural; | |
int duration = CONVERSIONS[i].duration; | |
int count = 0; | |
while(seconds - duration >= 0) | |
{ | |
seconds -= duration; | |
count++; | |
} | |
if(count == 0) | |
{ | |
result[i] = NULL; | |
} | |
else | |
{ | |
char* suffix = (count == 1 ? singular : plural); | |
result[i] = (char*)malloc((count > 0 ? (int) log10 ((double) count) + 1 : count) + strlen(suffix) + 2); | |
sprintf(result[i], "%d %s", count, suffix); | |
valid_results++; | |
} | |
} | |
if(valid_results > 1) | |
{ | |
int buffSize = 0; | |
for(unsigned int i = 0; i < TOTAL_CONVERSIONS; i++) | |
{ | |
if(result[i]) | |
{ | |
buffSize += strlen(result[i]); | |
} | |
} | |
char* string = (char*)malloc(buffSize + ((TOTAL_CONVERSIONS - 2) * 2) + 1); | |
for(unsigned int i = 0; i < TOTAL_CONVERSIONS - 1; i++) | |
{ | |
if(result[i]) | |
{ | |
char* suffix = (i < TOTAL_CONVERSIONS - 2 ? ", " : ""); | |
sprintf(string, "%s%s", result[i], suffix); | |
} | |
} | |
char* ret = (char*)malloc(strlen(string) + 5 + strlen(result[TOTAL_CONVERSIONS - 1]) + 1); | |
sprintf(ret, "%s and %s", string, result[TOTAL_CONVERSIONS - 1]); | |
for(unsigned int i = 0; i < TOTAL_CONVERSIONS; i++) | |
{ | |
if(result[i]) | |
{ | |
free(result[i]); | |
} | |
} | |
free(string); | |
return ret; | |
} | |
else if(valid_results > 0) | |
{ | |
return result[0]; | |
} | |
else | |
{ | |
char* ret = (char*)malloc(1); | |
strcpy(ret, ""); | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment