Advent of Code 2022 - 3

Day 3: Rucksack Reorganization

https://adventofcode.com/2022/day/3

Part One

用 set 寫好了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
priority = 0
with open('03.txt', 'r') as fp:
for line in fp:
line = line.strip()
if len(line):
l = set(line[:len(line)//2])
r = set(line[len(line)//2:])
for c in r:
if c in l:
if ord(c) >= 97: # a-z
priority += ord(c) - 97 + 1
else: # A-Z
priority += ord(c) - 65 + 27
print(priority)

Answer: 7824

Part Two

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
priority = 0
with open('03.txt', 'r') as fp:
lines = fp.readlines()
idx = 0
while idx < len(lines):
a = set(lines[idx].strip())
b = set(lines[idx+1].strip())
c = set(lines[idx+2].strip())
for i in range(26):
t = chr(ord('a')+i)
if t in a and t in b and t in c:
priority += ord(c) - 97 + 1
continue
t = chr(ord('A')+i)
if t in a and t in b and t in c:
priority += ord(c) - 65 + 27
continue
idx += 3
print(priority)

Answer: 2798