Skip to content

Commit

Permalink
[Julia] Day 24 brute-force
Browse files Browse the repository at this point in the history
  • Loading branch information
Moelf committed Dec 24, 2023
1 parent e41c4d1 commit efb6744
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@ name = "AoC2023"
uuid = "6a329b9a-879f-4671-b49f-bf1b928a466a"
authors = ["all authors"]
version = "0.1.0"

[deps]
NonlinearSolve = "8913a72c-1f9b-4ce2-8d82-65094dcecaec"
5 changes: 5 additions & 0 deletions inputs/24_example.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
19, 13, 30 @ -2, 1, -2
18, 19, 22 @ -1, -1, -2
20, 25, 34 @ -2, -2, -4
12, 31, 28 @ -1, -2, -1
20, 19, 15 @ 1, -5, -3
2 changes: 2 additions & 0 deletions solutions/24_moelf.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
17867
557743507346379
83 changes: 83 additions & 0 deletions src/julia/24_moelf.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
struct Hail
pos::NTuple{3,Int}
vel::NTuple{3,Int}
end

slopey(h) = big(h.vel[2]) / h.vel[1]
slopez(h) = big(h.vel[3]) / h.vel[1]
isfuture(h, x0) = sign(x0 - h.pos[1]) == sign(h.vel[1])

function intersect(h1, h2)
x1, y1 = h1.pos
x2, y2 = h2.pos
S1, S2 = slopey(h1), slopey(h2)
x0 = (y2 - y1 - S2 * x2 + S1 * x1) / (S1 - S2)
y0 = (x0 - x1) * S1 + y1

x0, y0
end

function forecast(h, x0)
x, y, z = h.pos
Sy = slopey(h)
Sz = slopez(h)
Δy = (x0 - x) * Sy
Δz = (x0 - x) * Sz
return (x0, y + Δy, z + Δz)
end

function impl2(hails, v_extrema)
xlim, ylim, zlim = v_extrema
for xi in range(xlim...), yi in 0:100
v_offset = (xi, yi, 0)
dummy = [Hail(x.pos, x.vel .- v_offset) for x in hails]
h1, rest... = dummy
xy = intersect(h1, rest[1])
x0 = xy[1]
isinf(x0) && continue
if all(h -> all(intersect(h1, h) .≈ xy), rest)
for zi in range(zlim...)
v_offset = (xi, yi, zi)
dummy2 = [Hail(x.pos, x.vel .- v_offset) for x in hails]
h2, rest2... = dummy2
est = forecast(h2, x0)
if all(h -> all(forecast(h, x0) .≈ est), rest2)
return sum(round.(BigInt, est))
end
end
end
end
error("no solution")
end

function main(path)
vs = Int[]

hails = map(eachline(path)) do line
l, r = split(line, " @ ")
pos = Tuple(parse.(Int, split(l, ", ")))
vel = Tuple(parse.(Int, split(r, ", ")))
append!(vs, vel)
Hail(pos, vel)
end

v_extrema = extrema.(eachrow(reshape(vs, 3, :)))

p1 = 0
for i in eachindex(hails), j in i+1:lastindex(hails)
h1 = hails[i]
h2 = hails[j]
x0, y0 = intersect(h1, h2)
!isfuture(h1, x0) && continue
!isfuture(h2, x0) && continue
if all(x -> 200000000000000 <= x <= 400000000000000, (x0, y0))
p1 += 1
end
end
println(p1)

println(impl2(hails, v_extrema))
end


(abspath(PROGRAM_FILE) == @__FILE__) && main(ARGS[1])

0 comments on commit efb6744

Please sign in to comment.