Skip to content

Commit 5c3fef2

Browse files
committed
day6
1 parent 3440f2a commit 5c3fef2

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

2023/day6.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from common import ai
2+
from math import sqrt, ceil, floor
3+
4+
inp = """
5+
Time: 7 15 30
6+
Distance: 9 40 200
7+
"""
8+
9+
def parse_p1(inp):
10+
res = []
11+
for l in inp.strip().split("\n"):
12+
a,ns = l.split(':')
13+
res.append(list(map(int, ns.strip().split())))
14+
assert len(res) == 2
15+
return res
16+
17+
def p1(inp):
18+
ts, ds = inp
19+
ways = 1
20+
for t,d in zip(ts, ds):
21+
print(f"race t {t} record d {d}")
22+
23+
# known t,d unknown time charging, tc
24+
# d = ts*speed where ts=t-tc, speed=tc
25+
# = (t-tc)*tc
26+
# = t*tc - tc*tc
27+
# 0 = -1*tc^2 +t*tc -d
28+
# solve roots by quadratic eqn a=-1, b=t, c=-d, x=tc
29+
# tc = (-b +- sqrt(bb - 4ac)))/2a
30+
# tc = (-t +- sqrt(tt - 4*d))/-2
31+
# tc = (t +- sqrt(tt - 4d)) /2
32+
tc_p = (t + sqrt(t*t - 4*d))/2
33+
tc_m = (t - sqrt(t*t - 4*d))/2
34+
tc_m = ceil(tc_m)
35+
tc_p = floor(tc_p)
36+
print(f"tc={tc_m} tc={tc_p}")
37+
38+
# need to beat the record, not match it exactly.
39+
# nudge by 1 more towards max distance
40+
while tc_m * (t-tc_m) <= d:
41+
tc_m += 1
42+
while tc_p * (t-tc_p) <= d:
43+
tc_p -= 1
44+
print(f"after inequality adjustment {tc_m} - {tc_p}")
45+
ways = ways * (tc_p - tc_m + 1)
46+
return ways
47+
48+
ai(p1(parse_p1(inp)), 288)
49+
ai(p1(parse_p1(open("day6.txt").read())), 1710720)
50+
51+
# stupid part2 parser without spaces
52+
def parse_p2(inp):
53+
res = []
54+
for l in inp.strip().split("\n"):
55+
a,ns = l.split(':')
56+
ns = ns.replace(" ", "")
57+
res.append(list(map(int, ns.strip().split())))
58+
assert len(res) == 2
59+
return res
60+
61+
ai(p1(parse_p2(inp)), 71503)
62+
ai(p1(parse_p2(open("day6.txt").read())), 35349468)

2023/day6.txt

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Time: 56 97 77 93
2+
Distance: 499 2210 1097 1440

0 commit comments

Comments
 (0)