summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2022/aoc-25/main.c
blob: c88d9188d24d7ecda8c61ef5feabb710d3ac798a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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;
}