diff options
author | kartofen <mladenovnasko0@gmail.com> | 2023-02-10 23:53:15 +0200 |
---|---|---|
committer | kartofen <mladenovnasko0@gmail.com> | 2023-02-10 23:53:15 +0200 |
commit | 555091332de32b1d3b36c888ed21898aae540750 (patch) | |
tree | 6dd5dc02ecb4d7678d13e5f1265e61e155f33c43 /Advent-of-Code-2022/aoc-25/main.c | |
parent | 9f57e15a054b16d335e9d5c49ddd7be829b4e272 (diff) |
add a couple of days
Diffstat (limited to 'Advent-of-Code-2022/aoc-25/main.c')
-rw-r--r-- | Advent-of-Code-2022/aoc-25/main.c | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/Advent-of-Code-2022/aoc-25/main.c b/Advent-of-Code-2022/aoc-25/main.c new file mode 100644 index 0000000..c88d918 --- /dev/null +++ b/Advent-of-Code-2022/aoc-25/main.c @@ -0,0 +1,89 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#if 0 + #define FILENAME "sample.txt" +#else + #define FILENAME "input.txt" +#endif + +int char_to_int[256] = { + ['1'] = 1, + ['2'] = 2, + ['0'] = 0, + ['-'] = -1, + ['='] = -2 +}; + +char int_to_char[5] = { + '=', '-', '0', '1', '2' +}; + +long long sum = 0; + +void encode() +{ + signed char num[1000] = {0}; + size_t num_sz = 0; + + for(long long n = sum; n > 0; n /= 5, num_sz++) { + num[num_sz] += n % 5; + num[num_sz+1] += num[num_sz]/5; + num[num_sz] %= 5; + + if(num[num_sz] == 3) { + num[num_sz] = -2; + num[num_sz+1] += 1; + } else if(num[num_sz] == 4) { + num[num_sz] = -1; + num[num_sz+1] += 1; + } + } + + for(int i = num_sz-1; i >= 0; i--) { + printf("%c", int_to_char[num[i]+2]); + } + + printf("\n"); +} + +long long decode(char *num) +{ + long long n = 0; + + size_t len = strlen(num); + long long power_of_5 = 1; + + for(int i = len-1; i >= 0; i--) { + n += power_of_5 * char_to_int[num[i]]; + power_of_5 *= 5; + } + + return n; +} + +void parse() +{ + FILE *fp = fopen(FILENAME, "r"); + if(!fp) { + fprintf(stderr, "ERROR: Could not open file %s\n", FILENAME); + exit(1); + } + + char line[256]; + while(fgets(line, sizeof(line), fp) != NULL) { + if(line[strlen(line)-1] == '\n') + line[strlen(line)-1] = '\0'; + sum += decode(line); + } + + fclose(fp); +} + +int main(void) +{ + parse(); + encode(); + return 0; +} |