2018 - Day 2 (Inventory Management System)

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
#!/usr/bin/env python3

#Advent of Code
#2018 Day 2, 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):
    twos = 0
    threes = 0

    for i in puzzle_input:
        if sum([1 for x in string.ascii_lowercase if i.count(x) == 2]) >= 1:
            twos += 1

        if sum([1 for x in string.ascii_lowercase if i.count(x) == 3]) >= 1:
            threes += 1
    
    return twos * threes

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

    checksum = solve(puzzle_input)

    print("The checksum is " + str(checksum) + ".")

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        self.assertEqual(solve(["abcdef"
                                "bababc",
                                "abbcde",
                                "abcccd",
                                "aabcdd",
                                "abcdee",
                                "ababab"]), 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
38
39
40
41
42
43
44
45
#!/usr/bin/env python3

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

from itertools import combinations

def solve(puzzle_input):
    for pair in combinations(puzzle_input, 2):
        diff = 0
        last_index = None

        for i, c in enumerate(pair[0]):
            if c != pair[1][i]:
                diff += 1
                last_index = i

        if diff == 1:
            return pair[0][:last_index] + pair[0][last_index+1:]

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

    letters = solve(puzzle_input)

    print("The letters in common are " + str(letters) + ".")

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        self.assertEqual(solve(["abcde",
                                "fghij",
                                "klmno",
                                "pqrst",
                                "fguij",
                                "axcye",
                                "wvxyz"]), "fgij")

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