advent-of-code/2022/3/3.py
2022-12-03 10:41:47 +01:00

39 lines
No EOL
999 B
Python

"""
find an prioritize common items in two halves of strings
"""
import numpy as np
from string import ascii_letters
def compartments(rucksack:str):
t = rucksack.strip()
l = len(t)//2
return t[:l], t[l:]
def find_common(*comps:str) -> str:
cs = [set(c) for c in comps]
return cs[0].intersection(*cs[1:]).pop()
priority = dict(zip(ascii_letters, range(1,53)))
with open('2022/3/rucksacks.txt') as filein:
lines = [line.strip() for line in filein.readlines()]
test = """vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw"""
# lines = test.splitlines(keepends=False)
rucksacks = [compartments(line) for line in lines]
print(sum([priority[find_common(*rucksack)] for rucksack in rucksacks]))
"""
find an prioritize common items in three stringlines
"""
groups = np.array(lines).reshape(-1,3)
badges = [priority[find_common(*group)] for group in groups]
print(sum(badges))