advent-of-code/2023/python/day06.py
2023-12-06 09:44:07 -05:00

69 lines
1.7 KiB
Python

import matrix
import shared
from dataclasses import dataclass
from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator
@dataclass
class Game:
duration: int
highscore: int
# @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):
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]))]
ways = []
for game in [Game(*g) for g in zip(times, distances)]:
ways.append(calculate(game))
print(reduce(operator.mul, ways, 1))
def calculate(game):
starting_win = None
for held in range(game.duration+1):
starting_win = held
remaining = game.duration - held
score = held * remaining
if score > game.highscore:
break
ending_win = None
for held in reversed(range(game.duration+1)):
ending_win = held
remaining = game.duration - held
score = held * remaining
if score > game.highscore:
break
print(game, starting_win, ending_win)
return ending_win+1-starting_win
def main():
rows = [row for row in shared.load_rows(6)]
with shared.elapsed_timer() as elapsed:
part1(rows)
print("🕒", elapsed())
rows = [row for row in shared.load_rows(6,True)]
with shared.elapsed_timer() as elapsed:
part2(rows)
print("🕒", elapsed())
if __name__ == "__main__":
main()