Last active
December 20, 2020 16:25
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Input ####################################################################### | |
str = read(open("/home/chubbc/Dropbox/Prog/Advent/2020/20.txt"),String); | |
tiles = Dict{Int,Matrix{Char}}(); | |
for rawtile∈split(str,"\n\n") | |
n = parse(Int,rawtile[6:9]); | |
tiles[n] = Matrix{Char}(undef,10,10); | |
for x∈1:10, y∈1:10 | |
tiles[n][x,y] = rawtile[x+11y]; | |
end | |
end | |
## Part 1 ###################################################################### | |
reorient(tile::Matrix{Char}, i::Int) = | |
i<0 ? rotl90(reverse(tile,dims=1),i) : rotl90(tile,i); | |
matchUD(t1::Tuple{Int,Int}, t2::Tuple{Int,Int}) = | |
(reorient(tiles[t1[1]],t1[2])[end,:]==reorient(tiles[t2[1]],t2[2])[1,:]); | |
matchLR(t1::Tuple{Int,Int}, t2::Tuple{Int,Int}) = | |
(reorient(tiles[t1[1]],t1[2])[:,end]==reorient(tiles[t2[1]],t2[2])[:,1]); | |
function populate(x::Int, y::Int) | |
for k∈setdiff(keys(tiles),first.(state)), i∈-4:3 | |
state[x,y] = (k,i); | |
if (y==1||matchUD(state[x,y-1],state[x,y])) && (x==1||matchLR(state[x-1,y],state[x,y])) | |
if (x,y)==size(state) || populate(mod1(x+1,size(state,1)), y+(x==size(state,1))) | |
return true; | |
end | |
end | |
end | |
state[x,y] = (0,0); | |
return false; | |
end | |
N = Int(√length(tiles)); | |
state = fill((0,0),N,N); | |
populate(1, 1); | |
p1 = prod(first.(state[[1,end],[1,end]])); | |
## Part 2 ###################################################################### | |
image = Matrix{Char}(undef,8*N,8*N); | |
for x∈1:N, y∈1:N | |
t = reorient(tiles[state[x,y][1]], state[x,y][2]); | |
image[(1:8).+8*(x-1),(1:8).+8*(y-1)] = permutedims(t[2:end-1,2:end-1]); | |
end | |
monster= | |
"..................#." * | |
"#....##....##....###" * | |
".#..#..#..#..#..#..."; | |
monster = reshape(collect(monster),(20,3)); | |
maxmons=0; | |
for i∈-4:3 | |
global maxmons, image, monster; | |
image2 = reorient(image,i); | |
mons = 0; | |
for x∈1:size(image2,1)-size(monster,1)+1, y∈1:size(image2,2)-size(monster,2)+1 | |
found = true; | |
for xx∈1:size(monster,1), yy∈1:size(monster,2) | |
if monster[xx,yy]=='#' && image2[x+xx-1,y+yy-1]!='#' | |
found = false; | |
end | |
end | |
mons += found; | |
end | |
maxmons = max(maxmons,mons); | |
end | |
p2 = count(image.=='#')-maxmons*count(monster.=='#'); | |
## Output ###################################################################### | |
println((p1,p2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment