2018 - Day 5 (Alchemical Reduction)

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python3

#Advent of Code
#2018 Day 5, 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

import string

def solve(puzzle_input):
    def react(polymer):
        units = []
        for u in polymer:
            if len(units) > 0:
                if units[-1].swapcase() == u:
                    units.pop()
                else:
                    units.append(u)
            else:
                units.append(u)
        return "".join(units)

    return len(react(puzzle_input))

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

    units = solve(puzzle_input)

    print("The number of remaining units is " + str(units) + ".")

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        self.assertEqual(solve("aA"), 0)

    def test_ex2(self):
        self.assertEqual(solve("abBA"), 0)

    def test_ex3(self):
        self.assertEqual(solve("abAB"), 4)

    def test_ex4(self):
        self.assertEqual(solve("aabAAB"), 6)

    def test_ex5(self):
        self.assertEqual(solve("dabAcCaCBAcCcaDA"), 10)

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
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python3

#Advent of Code
#2018 Day 5, 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

import string

def solve(puzzle_input):
    def react(polymer):
        units = []
        for u in polymer:
            if len(units) > 0:
                if units[-1].swapcase() == u:
                    units.pop()
                else:
                    units.append(u)
            else:
                units.append(u)
        return "".join(units)

    lengths = []
    for u in string.ascii_lowercase:
        if u in puzzle_input.lower():
            lengths.append(len(react(puzzle_input.replace(u, "").replace(u.upper(), ""))))
    
    return min(lengths)

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

    units = solve(puzzle_input)

    print("The length of the shortest polymer you can produce is " + str(units) + ".")

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        self.assertEqual(solve("dabAcCaCBAcCcaDA"), 4)

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