Skip to content

Instantly share code, notes, and snippets.

@mbeltagy
Created December 20, 2021 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbeltagy/ac65f927d161860d65c198f577d088e2 to your computer and use it in GitHub Desktop.
Save mbeltagy/ac65f927d161860d65c198f577d088e2 to your computer and use it in GitHub Desktop.
AoC 20 Trench Map
lines = readlines("input20.txt")
algo = lines[1]|> x->[c=='.' ? false : true for c in x]
imag = lines[3:end] .|> (x->[c=='.' ? false : true for c in x]) |> x->hcat(x...)
# pad the image by zeroes to simulate the infnitued
function pad(imag,pad)
oldsize = size(imag)
newsize = oldsize .+ 2*pad
new_imag = zeros(eltype(imag), newsize...)
new_imag[pad+1:oldsize[1]+pad,pad+1:oldsize[2]+pad] .= imag
new_imag
end
function outside(pos, Ifirst, Ilast )
(any(pos.I .< Ifirst.I) || any(pos.I .> Ilast.I)) && return true
false
end
function enhance(imag,algo, background=0)
out = similar(imag)
R = CartesianIndices(imag)
Ifirst, Ilast = first(R), last(R)
I1 = oneunit(Ifirst)
for pos in R
n = 0 % UInt16
for element in pos-I1:pos+I1
if outside(element, Ifirst, Ilast )
n = (n<<1) + (background%UInt16)
else
n = (n<<1) + (imag[element]%UInt16)
end
end
n += 1
out[pos] = algo[n]
end
out
end
# Part 1
padded_imag = pad(imag,2)
out = enhance(padded_imag ,algo)
out = enhance(out,algo, 1)
println("Part one: $(sum(out))")
# Now for part 2
out = pad(imag,50)
for i=1:50
out = enhance(out,algo, (i-1)%2)
end
println("Part two: $(sum(out))")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment