Day 10
file:test/Day10Spec.jl
# add tests
file:src/Day10.jl
module Day10
const nb = CartesianIndex.([(-1, 0), (0, -1), (1, 0), (0, 1)])
function neighbours(input::Matrix{Int}, a::CartesianIndex{2})
inbounds(b) = checkbounds(Bool, input, b)
legal(b) = inbounds(b) && input[b] - input[a] == 1
filter(legal, a .+ nb)
end
function trail_head_score(input::Matrix{Int}, a::CartesianIndex{2})
= CartesianIndex{2}[a]
s = zeros(Bool, size(input)...)
v = 0
score while !isempty(s)
= pop!(s)
x
if input[x] == 9
+= 1
score continue
end
for n in neighbours(input, x)
&& continue
v[n] pushfirst!(s, n)
= true
v[n] end
end
return score
end
function scores(input::Matrix{Int})
= zeros(Int, size(input)...)
result .==9] .= 1
result[inputfor x = 8:-1:0
for p in keys(result)
== x || continue
input[p] for n in neighbours(input, p)
+= result[n]
result[p] end
end
end
return result
end
read_input(io::IO) = readlines(io) .|> collect .|> (l->l.-'0') |> stack
function main(io::IO)
= read_input(io)
input = sum(trail_head_score(input, x) for x in keys(input)
part1 if input[x] == 0)
= sum(scores(input)[input .== 0])
part2 return part1, part2
end
end