62 lines
1.6 KiB
Python
62 lines
1.6 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):
|
|
# join ints
|
|
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 search(game, _range):
|
|
for held in _range:
|
|
remaining = game.duration - held
|
|
score = held * remaining
|
|
if score > game.highscore:
|
|
return held
|
|
|
|
def calculate(game):
|
|
starting_win = search(game, range(game.duration+1))
|
|
ending_win = search(game, reversed(range(game.duration+1)))
|
|
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()
|