Skip to content

Commit

Permalink
[Julia] Day 18 (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
Moelf authored Dec 18, 2023
1 parent 28916b1 commit d19b46a
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
14 changes: 14 additions & 0 deletions inputs/18_example.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
R 6 (#70c710)
D 5 (#0dc571)
L 2 (#5713f0)
D 2 (#d2c081)
R 2 (#59c680)
D 2 (#411b91)
L 5 (#8ceee2)
U 2 (#caa173)
L 1 (#1b58a2)
U 2 (#caa171)
R 2 (#7807d2)
U 3 (#a77fa3)
L 2 (#015232)
U 2 (#7a21e3)
2 changes: 2 additions & 0 deletions solutions/18_example.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
62
952408144115
2 changes: 2 additions & 0 deletions solutions/18_moelf.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
56678
79088855654037
58 changes: 58 additions & 0 deletions src/julia/18_moelf.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const CI = CartesianIndex{2}
const L, R, U, D = CI(0, -1), CI(0, 1), CI(-1, 0), CI(1, 0)
const DIRS = Dict(
"R" => R, "D" => D, "L" => L, "U" => U,
'0' => R, '1' => D, '2' => L, '3' => U)

function make_poly(dirs, nums)
POS = CI(0, 0)
PATH = CI[]
for (D, N) in zip(dirs, nums)
for _ in 1:N
POS += D
push!(PATH, POS)
end
end
return PATH
end
# https://en.wikipedia.org/wiki/Shoelace_formula
function shoelace(poly)
a = 0
for i in 1:lastindex(poly)-1
p1 = poly[i]
p2 = poly[i+1]
a += p1[1] * p2[2] - p2[1] * p1[2]
end
return abs(a ÷ 2)
end
# https://en.wikipedia.org/wiki/Pick's_theorem
function in_area(poly)
A = shoelace(poly)
b = length(poly)
return A + 1 - b ÷ 2
end

function impl(dirs, nums)
poly = make_poly(dirs, nums)
return in_area(poly) + length(poly)
end

function main(path)
M_str = stack(split.(readlines(path)); dims=1)
dir_str, num_str, color_str = eachcol(M_str)

dirs = [DIRS[s] for s in dir_str]
nums = parse.(Int, num_str)
println(impl(dirs, nums))

empty!(dirs); empty!(nums)

for s in color_str
num_str..., dir_str = replace(s, r"(#|\)|\()" => "")
push!(dirs, DIRS[dir_str])
push!(nums, parse(Int, num_str; base=16))
end
println(impl(dirs, nums))
end

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

0 comments on commit d19b46a

Please sign in to comment.