advent-of-code/2023/python/day06.py

65 lines
1.6 KiB
Python
Raw Permalink Normal View History

2023-12-06 14:44:07 +00:00
import matrix
import shared
from dataclasses import dataclass
2023-12-08 18:42:42 +00:00
from functools import reduce # Valid in Python 2.6+, required in Python 3
2023-12-06 14:44:07 +00:00
import operator
@dataclass
class Game:
duration: int
highscore: int
2023-12-08 18:42:42 +00:00
2023-12-06 14:44:07 +00:00
# @shared.profile
def part1(rows):
times = [int(r) for r in rows[0].split(":")[1].split(" ") if r]
distances = [int(r) for r in rows[1].split(":")[1].split(" ") if r]
ways = []
for game in [Game(*g) for g in zip(times, distances)]:
ways.append(calculate(game))
print(reduce(operator.mul, ways, 1))
# @shared.profile
def part2(rows):
2023-12-06 14:47:55 +00:00
# join ints
2023-12-06 14:44:07 +00:00
times = [int("".join([r for r in rows[0].split(":")[1].split(" ") if r]))]
distances = [int("".join([r for r in rows[1].split(":")[1].split(" ") if r]))]
2023-12-06 14:47:55 +00:00
2023-12-06 14:44:07 +00:00
ways = []
for game in [Game(*g) for g in zip(times, distances)]:
ways.append(calculate(game))
print(reduce(operator.mul, ways, 1))
2023-12-08 18:42:42 +00:00
2023-12-06 14:47:55 +00:00
def search(game, _range):
for held in _range:
2023-12-06 14:44:07 +00:00
remaining = game.duration - held
score = held * remaining
if score > game.highscore:
2023-12-08 18:42:42 +00:00
return held
2023-12-06 14:44:07 +00:00
2023-12-06 14:47:55 +00:00
def calculate(game):
2023-12-08 18:42:42 +00:00
starting_win = search(game, range(game.duration + 1))
ending_win = search(game, reversed(range(game.duration + 1)))
2023-12-06 14:44:07 +00:00
print(game, starting_win, ending_win)
2023-12-08 18:42:42 +00:00
return ending_win + 1 - starting_win
2023-12-06 14:44:07 +00:00
def main():
rows = [row for row in shared.load_rows(6)]
with shared.elapsed_timer() as elapsed:
part1(rows)
print("🕒", elapsed())
2023-12-08 18:42:42 +00:00
rows = [row for row in shared.load_rows(6, True)]
2023-12-06 14:44:07 +00:00
with shared.elapsed_timer() as elapsed:
part2(rows)
print("🕒", elapsed())
if __name__ == "__main__":
main()