summaryrefslogtreecommitdiff
path: root/08/main.py
blob: bfd5b0890388289924992c8ad48bff28c5b66b50 (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
#!/usr/bin/python



def solve_part1(lines):
    result = 0

    for line in lines:
        len_code = len(line)

        len_data = 0
        i = 0
        while i < len(line):
            if line[i] == "\"":
                pass
            elif line[i] == "\\":
                if line[i + 1] == "\"" or line[i + 1] == "\\":
                    len_data += 1
                    i += 1
                elif line[i + 1] == "x":
                    len_data += 1
                    i += 3
            else:
                len_data += 1
            i += 1

        result += len_code - len_data

    return result



def solve_part2(lines_old):
    # Escape all the provided strings once
    lines_new = []
    for old in lines_old:
        new = "\""
        for c in old:
            if c == "\"":
                new += "\\\""
            elif c == "\\":
                new += "\\\\"
            else:
                new += c
        new += "\""
        lines_new.append(new)

    # Then we can just run part 1 on the new input
    return solve_part1(lines_new)



def main():
    # Read (escaped) strings from input text file
    with open("input.txt", "r") as f:
        lines = f.read().splitlines()

    print("Part 1 solution:", solve_part1(lines)) # 1333 for me
    print("Part 2 solution:", solve_part2(lines)) # 2046 for me



if __name__ == "__main__":
    main()