day6 part 1 and 2
This commit is contained in:
parent
7311255b77
commit
a4ca5f4a4a
2
2023/full/day06.txt
Normal file
2
2023/full/day06.txt
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
Time: 56 71 79 99
|
||||||
|
Distance: 334 1135 1350 2430
|
68
2023/python/day06.py
Normal file
68
2023/python/day06.py
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
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()
|
2
2023/samples/day06.txt
Normal file
2
2023/samples/day06.txt
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
Time: 7 15 30
|
||||||
|
Distance: 9 40 200
|
Loading…
Reference in New Issue
Block a user