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

62 lines
1.6 KiB
Python
Raw Normal View History

2023-12-06 14:44:07 +00:00
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):
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-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-06 14:47:55 +00:00
return held
2023-12-06 14:44:07 +00:00
2023-12-06 14:47:55 +00:00
def calculate(game):
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)
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()