From 880758c7d5d805440e2239080840486503013bf8 Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Thu, 29 Dec 2022 09:51:45 +0000 Subject: Solve puzzle 25 part 1 --- 25.c | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 25.c (limited to '25.c') diff --git a/25.c b/25.c new file mode 100644 index 0000000..b0f7293 --- /dev/null +++ b/25.c @@ -0,0 +1,100 @@ + +#include + + +// Only works for positive numbers so far! +char * +snafu(char * dest, size_t len, long n) +{ + size_t i = 0, j; + + // Build string in reverse. + while (n && i < len) { + int d = n % 5; + + switch (d) { + case 0: + case 1: + case 2: + dest[i++] = '0' + d; + break; + + case 3: + dest[i++] = '='; + n += 5; + break; + + case 4: + dest[i++] = '-'; + n += 5; + break; + } + + n /= 5; + } + + dest[i] = '\0'; + + // Reverse string to be right way around + for (j = 0; j < i / 2; ++j) { + char tmp = dest[j]; + dest[j] = dest[i - 1 - j]; + dest[i - 1 - j] = tmp; + } + + return dest; +} + + +int +main() +{ + long i = 0, total = 0; + int c; + char buf[BUFSIZ]; + + while ((c = fgetc(stdin)) != EOF) { + switch (c) { + case '2': + i *= 5; + i += 2; + break; + + case '1': + i *= 5; + i += 1; + break; + + case '0': + i *= 5; + break; + + case '-': + i *= 5; + i -= 1; + break; + + case '=': + i *= 5; + i -= 2; + break; + + case '\n': +#if 0 + fprintf(stderr, "%s (%ld)\n", snafu(buf, sizeof(buf), i), i); +#endif + total += i; + i = 0; + break; + + default: + fprintf(stderr, "Unexpected input: %c\n", c); + return -1; + } + } + + printf("Total: %s (%ld)\n", snafu(buf, sizeof(buf), total), total); + + return 0; +} + -- cgit v1.2.1