2022-12-03 - Rucksack Reorganization
(original .ipynb)
Day 3 puzzle input is a list of ascii strings which represent a rucksacks with two compartments that contains some items (mine is here). Part 1 involves looking at each rucksack's contents, finding how many items occur in both compartments and summing the results for all rucksacks. Part 2 is taking groups of three rucksacks, finding how many items occur in any compartment in all three - then calculating the sum of these for all groups.
puzzle_input_str = open("./puzzle_input/day3.txt").read()
test_input_str = """vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw"""
def get_priority(item):
c = ord("A") if item.isupper() else ord("a")
base = 27 if item.isupper() else 1
return ord(item) + base - c
def sum_items_both_compartments(comp1, comp2):
s1, s2 = set(comp1), set(comp2)
return sum(get_priority(i) for i in s1.intersection(s2))
def parse_rucksack(line):
mid = int(len(line)/2)
return line[:mid], line[mid:]
def part_one(input_str):
return sum(
sum_items_both_compartments(*parse_rucksack(line))
for line
in input_str.split("\n")
)
assert 157 == part_one(test_input_str)
print("part one:", part_one(puzzle_input_str))
part one: 7821
def part_two(input_str):
rucksacks = [set(line) for line in input_str.split("\n")]
total = 0
for i in list(range(0, len(rucksacks), 3)):
badge = rucksacks[i].intersection(rucksacks[i+1]).intersection(rucksacks[i+2])
total += get_priority(badge.pop())
return total
assert 70 == part_two(test_input_str)
print("part two:", part_two(puzzle_input_str))
part two: 2752