2015 - Day 8 (Matchsticks)

View puzzle description on AdventOfCode.com
Part 1
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
#!/usr/bin/env python3

#Advent of Code
#2015 Day 8, Part 1
#Solution by James C. (https://github.com/JamesMCo)

import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run

def solve(puzzle_input):
    literals = 0
    memory = 0

    for i in puzzle_input:
        literals += len(i)
        memory += len(eval(i))

    return literals - memory

def main():
    puzzle_input = util.read.as_lines()

    v = solve(puzzle_input)

    print("The number of characters of code for literals minus the values of the strings is " + str(v) + ".")

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        return self.assertEqual(solve(["\"\"",
                                       "\"abc\"",
                                       "\"aaa\\\"aaa\"",
                                       "\"\\x27\""]), 12)

if __name__ == "__main__":
    run(main)
Part 2
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
#!/usr/bin/env python3

#Advent of Code
#2015 Day 8, Part 2
#Solution by James C. (https://github.com/JamesMCo)

import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run

def solve(puzzle_input):
    literals = 0
    encoded = 0

    for i in puzzle_input:
        literals += len(i)
        encoded += len("\""+i.replace('"', '/"').replace("\\", "\\\\").replace("/", "\\")+"\"")

    return encoded - literals

def main():
    puzzle_input = util.read.as_lines()

    v = solve(puzzle_input)

    print("The number of characters of code for encoded strings minus number of characters of code for literals is " + str(v) + ".")

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        return self.assertEqual(solve(["\"\"",
                                       "\"abc\"",
                                       "\"aaa\\\"aaa\"",
                                       "\"\\x27\""]), 19)

if __name__ == "__main__":
    run(main)
Return to solution index