Skip to content
advent of code 2022

day 03

rucksack reorganization

approach

part 1 cuts each line in half, turns both halves into sets and takes the one character in their intersection. a small priority function maps lowercase letters to 1–26 and uppercase to 27–52.

part 2 walks the lines in chunks of three and intersects all three sets to find the shared character. the rust version is a port of the same idea.

the trick

the item in common is a set intersection with exactly one element, and the priority is an offset from ord.

python
def find_incorrect(s):
    m = len(s) >> 1
    l, r = set(s[:m]), set(s[m:])
    return (l & r).pop()

def priority(c):
    if c.isupper():
        return ord(c) - ord('A') + 27
    else:
        return ord(c) - ord('a') + 1