55 lines
1.4 KiB
Julia
55 lines
1.4 KiB
Julia
include("utils.jl")
|
|
|
|
function parse_input(filename)
|
|
line = collect(non_empty_lines(filename))[1]
|
|
println(line)
|
|
map(x->parse(Int, x.match), eachmatch(r"-?[0-9]+", line))
|
|
end
|
|
|
|
function inverse_gauss(x)
|
|
sqrt(1/4 + 2 * x) - 1/2
|
|
end
|
|
|
|
function valid_x_velocities(left, right)
|
|
Int64(ceil(inverse_gauss(left))):Int64(floor(inverse_gauss(right)))
|
|
end
|
|
|
|
function hitp(left, right, bottom, top, vel)
|
|
pos = [0, 0]
|
|
mpos = [0, 0]
|
|
velocity = copy(vel)
|
|
while pos[2] > bottom
|
|
pos += velocity
|
|
mpos = max(pos, mpos)
|
|
velocity[1] = velocity[1] > 0 ? velocity[1] - 1 : 0
|
|
velocity[2] -= 1
|
|
|
|
if pos[1] >= left && pos[1] <= right && pos[2] >= bottom && pos[2] <= top
|
|
return true, mpos[2], vel
|
|
end
|
|
end
|
|
false, mpos[2], vel
|
|
end
|
|
|
|
function solution17_1()
|
|
left, right, bottom, top = parse_input("17.data")
|
|
for vx in valid_x_velocities(left, right)
|
|
shots = map(v->hitp(left, right, bottom, top, v), [[vx, vy] for vy in 1:10000])
|
|
hits = collect(Iterators.filter(x->x[1], shots))
|
|
println(last(sort(hits, by=x->x[2])))
|
|
end
|
|
end
|
|
|
|
function solution17_2()
|
|
left, right, bottom, top = parse_input("17.data")
|
|
sum = 0
|
|
for vx in 1:right
|
|
shots = map(v->hitp(left, right, bottom, top, v), [[vx, vy] for vy in bottom:1000])
|
|
hits = collect(map(x->x[3], Iterators.filter(x->x[1], shots)))
|
|
sum += length(hits)
|
|
end
|
|
sum
|
|
end
|
|
|
|
solution17_2()
|