advent-of-code/12023/06/06.lua

54 lines
1.0 KiB
Lua

io.input("input")
time_line = io.read()
distance_line = io.read()
times = {}
distances = {}
time2 = ""
dist2 = ""
for t in time_line:gmatch("%d+") do
table.insert(times, tonumber(t))
time2 = time2 .. t
end
for d in distance_line:gmatch("%d+") do
table.insert(distances, tonumber(d))
dist2 = dist2 .. d
end
time2 = tonumber(time2)
dist2 = tonumber(dist2)
function dist(tt, tp) return tp*(tt-tp) end
function count(d, t)
-- v = Tp
-- d = Tp*Tr = Tp*(t-Tp) = -Tp²+t*Tp
-- -Tp² + t*Tp - d = 0
t1 = math.ceil((-t+math.sqrt(t*t-4*d))/(-2))
t2 = math.floor((-t-math.sqrt(t*t-4*d))/(-2))
c = t2-t1+1
-- we only care when the distance is greater
if dist(t,t1)==d then c = c - 2 end --t2 will be an integer too
return c
end
mul1 = 1
for i, t in ipairs(times) do
d = distances[i]
--[[
count = 0
for tp = 0,t do
if dist(t,tp)>d then count = count + 1 end
end
--]]
c = count(d,t)
mul1 = mul1*c
print(t,d,c)
end
print("part 1", mul1)
print("part 2", count(dist2,time2))