aoc2022/d3.py

66 lines
1.4 KiB
Python
Raw Normal View History

2023-12-04 00:20:02 +01:00
from string import ascii_lowercase, ascii_uppercase
2023-12-04 00:05:09 +01:00
EXAMPLE = """
2023-12-04 00:20:02 +01:00
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
2023-12-04 00:05:09 +01:00
"""
2023-12-04 00:20:02 +01:00
def let_to_score(cin):
d = {}
for i, c in enumerate(ascii_lowercase):
d[c] = i + 1
for i, c in enumerate(ascii_uppercase):
d[c] = i + 27
return d[cin]
2023-12-04 00:05:09 +01:00
def clean(text: str) -> list[str]:
return list(filter(lambda l: l.strip() != "", text.splitlines()))
def solve(lines: list[str]):
s = 0
for (i, line) in enumerate(lines):
2023-12-04 00:20:02 +01:00
half = len(line) // 2
a, b = line[:half], line[half:]
a = set(a)
b = set(b)
z = a.intersection(b)
l = list(z)[0]
score = let_to_score(l)
s += score
# 8:42
2023-12-04 00:05:09 +01:00
return s
2023-12-04 00:20:02 +01:00
def get_score(l):
s = 0
s = set(l[0]).intersection(set(l[1])).intersection(set(l[2]))
s = list(s)[0]
return let_to_score(s)
2023-12-04 00:05:09 +01:00
def solve2(lines: list[str]):
s = 0
2023-12-04 00:20:02 +01:00
for i in range(0, len(lines), 3):
s += get_score(lines[i:i+3])
2023-12-04 00:05:09 +01:00
return s
def main():
example = clean(EXAMPLE)
print("Example 1:", solve(example))
data = clean(open("i3.txt").read())
print("Solution 1:", solve(data))
example = clean(EXAMPLE)
print("Example 2:", solve2(example))
data = clean(open("i3.txt").read())
print("Solution 2:", solve2(data))
2023-12-04 00:20:02 +01:00
# 13:08
2023-12-04 00:05:09 +01:00
if __name__ == "__main__":
main()