summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--25.c100
-rw-r--r--makefile1
2 files changed, 101 insertions, 0 deletions
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 <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;
+}
+
diff --git a/makefile b/makefile
index 8b29f4d..45e5299 100644
--- a/makefile
+++ b/makefile
@@ -26,6 +26,7 @@ all: bin \
bin/22 \
bin/23 \
bin/24 \
+ bin/25 \
bin:
mkdir -p $@