Add day 3 solution
This commit is contained in:
parent
d88f3742d1
commit
03233a6710
6
03/example
Normal file
6
03/example
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
vJrwpWtwJgWrhcsFMMfFFhFp
|
||||||
|
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
|
||||||
|
PmmdzqPrVvPwwTWBwg
|
||||||
|
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
|
||||||
|
ttgJtRGJQctTZtZT
|
||||||
|
CrZsJsPPZsGzwwsLwLmpwMDw
|
||||||
46
03/rucksacks.py
Normal file
46
03/rucksacks.py
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
|
||||||
|
import fileinput
|
||||||
|
|
||||||
|
from typing import Iterable
|
||||||
|
|
||||||
|
def letter_to_priority(i: str) -> int:
|
||||||
|
i = ord(i)
|
||||||
|
return (i & 0b11111) + (~((i & 0b00100000) >> 5) & 1) * 26
|
||||||
|
|
||||||
|
def compartment(items: str) -> int:
|
||||||
|
field = 0
|
||||||
|
for item in items:
|
||||||
|
field |= 1 << (letter_to_priority(item) - 1)
|
||||||
|
return field
|
||||||
|
|
||||||
|
def bitmap_to_priority(field: int) -> int:
|
||||||
|
for idx in range(52):
|
||||||
|
if field & 0b1:
|
||||||
|
return idx + 1
|
||||||
|
else:
|
||||||
|
field >>= 1
|
||||||
|
|
||||||
|
def solve(lines: Iterable[str]) -> int:
|
||||||
|
score = 0
|
||||||
|
for line in map(lambda x: x.strip(), lines):
|
||||||
|
items = len(line)
|
||||||
|
lh = compartment(line[:items//2])
|
||||||
|
rh = compartment(line[items//2:])
|
||||||
|
score += bitmap_to_priority(lh & rh)
|
||||||
|
return score
|
||||||
|
|
||||||
|
def solveb(lines: Iterable[str]) -> int:
|
||||||
|
score = 0
|
||||||
|
iterator = map(lambda x: x.strip(), lines.__iter__())
|
||||||
|
for first in iterator:
|
||||||
|
second = next(iterator)
|
||||||
|
third = next(iterator)
|
||||||
|
score += bitmap_to_priority(compartment(first) & compartment(second) & compartment(third))
|
||||||
|
return score
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print(solve(fileinput.input()))
|
||||||
|
print(solveb(fileinput.input()))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Loading…
Reference in New Issue
Block a user