From 1bf812ce9db606f43ca4ffcdb10700c70faa71dd Mon Sep 17 00:00:00 2001 From: Patrick Michl Date: Thu, 9 Dec 2021 07:22:03 +0100 Subject: [PATCH] solve and cleanup day9 --- src/day_9.jl | 88 +++++++++++++++++----------------------------------- 1 file changed, 29 insertions(+), 59 deletions(-) diff --git a/src/day_9.jl b/src/day_9.jl index 1a17115..cb76b8f 100644 --- a/src/day_9.jl +++ b/src/day_9.jl @@ -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 + 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 - push!(adjacent, map[i][j]) 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 - h2 = map[p[1]][p[2]] - if h2 < 9 && h2 > h - push!(visited, pos) - push!(queue, pos) + +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 h < h2 < 9 + push!(v, p) + push!(q, p) + end end end end end - return visited + 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