aoc2022/3/b.py

47 lines
1.4 KiB
Python

# All items of a given type are meant to go into exactly one of the two compartments.
# The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.
# Every item type is identified by a single lowercase or uppercase letter
# The list of items for each rucksack is given as characters all on a single line.
# A given rucksack always has the same number of items in each of its two compartments,
# so the first half of the characters represent items in the first compartment,
# while the second half of the characters represent items in the second compartment.
def get_prio(c):
# Lowercase item types a through z have priorities 1 through 26.
# Uppercase item types A through Z have priorities 27 through 52.
c = ord(c)
if c >= 97 and c <= 122:
return c - 96
return c - 38
total = 0
# Every Elf carries a badge that identifies their group.
# For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves.
with open("input.txt") as f:
while True:
lines = [f.readline().strip() for _ in range(0, 3)]
if not all(lines):
break
chars = [set() for _ in range(0, 3)]
for i, line in enumerate(lines):
for c in line:
chars[i].update(c)
common = chars[0].intersection(chars[1]).intersection(chars[2])
assert len(common) == 1
total += get_prio(common.pop())
print(total)