solve and cleanup day9

This commit is contained in:
Patrick Michl 2021-12-09 07:22:03 +01:00
parent bbd18bcfd0
commit 1bf812ce9d

View File

@ -4,87 +4,57 @@ using Pipe: @pipe
using Combinatorics
function p1(input::Vector{String})
map = []
for l in input
push!(map, [ parse(Int, c) for c in l ])
end
risks = 0
for x in 1:length(map)
for y in 1:length(map[1])
adjacent = []
for (a,b) in [[0,1], [1,0], [0,-1], [-1,0]]
i = x + a
j = y + b
if i < 1 || i > length(map) || j < 1 || j > length(map[1])
continue
end
push!(adjacent, map[i][j])
end
@info map[x][y]
@info adjacent
if map[x][y] < minimum(adjacent)
@info "low"
risks += map[x][y] + 1
end
end
end
return risks
end
function lowpoints(map)
low = []
low = Dict()
for x in 1:length(map)
for y in 1:length(map[1])
adjacent = []
for (a,b) in [[0,1], [1,0], [0,-1], [-1,0]]
i = x + a
j = y + b
if i < 1 || i > length(map) || j < 1 || j > length(map[1])
continue
end
for (i,j) in [ [x+i,y+j] for (i,j) in zip([0,1,0,-1], [1,0,-1,0]) ]
if i in 1:length(map) && j in 1:length(map[1])
push!(adjacent, map[i][j])
end
end
if map[x][y] < minimum(adjacent)
push!(low, [x,y])
low[[x,y]] = map[x][y]
end
end
end
return low
end
function search(map, pos)
queue = [pos]
visited = [pos]
function p1(input::Vector{String})
map = [ parse.(Int, collect(l)) for l in input ]
low = lowpoints(map)
return sum(values(low)) + length(low)
end
while length(queue) > 0
c = popfirst!(queue)
h = map[c[1], c[2]]
for pos in [ [x+i,y+j] for (i,j) in zip([0,1,0,-1], [1,0,-1,0]) ]
if p[1] < 1 || p[1] > length(map) || p[2] < 1 || p[2] > length(map[1])
continue
end
if pos visited
function search(map, pos)
q = [pos]
v = [pos]
while length(q) > 0
c = popfirst!(q)
h = map[c[1]][c[2]]
for p in [ [c[1]+i,c[2]+j] for (i,j) in zip([0,1,0,-1], [1,0,-1,0]) ]
if p[1] in 1:length(map) && p[2] in 1:length(map[1])
if p v
h2 = map[p[1]][p[2]]
if h2 < 9 && h2 > h
push!(visited, pos)
push!(queue, pos)
if h < h2 < 9
push!(v, p)
push!(q, p)
end
end
end
end
return visited
end
return v
end
function p2(input::Vector{String})
map = []
for l in input
push!(map, [ parse(Int, c) for c in l ])
end
map = [ parse.(Int, collect(l)) for l in input ]
low = lowpoints(map)
basin_sizes = [ length(search(map, p)) for p in low ]
basin_sizes = [ length(search(map, p)) for p in keys(low) ]
return prod(sort(basin_sizes)[end-2:end])
end