diff options
author | Adam Spragg <adam@spra.gg> | 2022-12-29 09:51:45 +0000 |
---|---|---|
committer | Adam Spragg <adam@spra.gg> | 2022-12-29 09:51:45 +0000 |
commit | 880758c7d5d805440e2239080840486503013bf8 (patch) | |
tree | 9ed6dce4cdaf68749a3d2c28ca64f41ee64b49e2 | |
parent | 1b3d46978fae3445a939fcba7252730c6885277b (diff) |
Solve puzzle 25 part 1
-rw-r--r-- | 25.c | 100 | ||||
-rw-r--r-- | makefile | 1 |
2 files changed, 101 insertions, 0 deletions
@@ -0,0 +1,100 @@ + +#include <stdio.h> + + +// 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; +} + @@ -26,6 +26,7 @@ all: bin \ bin/22 \ bin/23 \ bin/24 \ + bin/25 \ bin: mkdir -p $@ |