Last active
December 26, 2015 03:39
-
-
Save dpoggi/7087785 to your computer and use it in GitHub Desktop.
Roman numerals in C. Because, you know, yeah.
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
const char *g_numeral_list[] = {"M", "CM", "D", "CD", "C", "XC", | |
"L", "XL", "X", "IX", "V", "IV", "I"}; | |
const int g_value_list[] = {1000, 900, 500, 400, 100, 90, | |
50, 40, 10, 9, 5, 4, 1}; | |
const int g_list_length = 13; | |
const size_t g_buffer_size = 32; | |
void convert_to_numerals(int num, char **buffer) { | |
int i; | |
size_t total_buffer, max_chars; | |
total_buffer = g_buffer_size; | |
max_chars = g_buffer_size - 1; | |
for (i = 0; i < g_list_length; ++i) { | |
while (num >= g_value_list[i]) { | |
if (max_chars < 2) { | |
*buffer = (char *)realloc(*buffer, total_buffer + g_buffer_size); | |
memset(*buffer + total_buffer * sizeof(char), 0, g_buffer_size); | |
total_buffer += g_buffer_size; | |
max_chars += g_buffer_size; | |
} | |
strncat(*buffer, g_numeral_list[i], max_chars); | |
num -= g_value_list[i]; | |
max_chars -= strlen(g_numeral_list[i]); | |
} | |
} | |
} | |
int main(int argc, const char *argv[]) { | |
int num; | |
char *result; | |
if (argc < 2) { | |
printf("Usage: %s <num>\n", argv[0]); | |
return 0; | |
} | |
num = atoi(argv[1]); | |
if (num < 1) { | |
fprintf(stderr, "Error: invalid input (zero, negative, or NaN).\n"); | |
return 1; | |
} | |
result = (char *)calloc(g_buffer_size, sizeof(char)); | |
convert_to_numerals(num, &result); | |
printf("%s\n", result); | |
free(result); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Haters gonna hate on my global variables and my running the algo twice to figure out how much memory I need. Because oversized buffers are for quitters.
And by that I mean I really need to learn to use realloc.