Skip to content

Instantly share code, notes, and snippets.

@jordancluts
Created December 10, 2021 15:37
Show Gist options
  • Save jordancluts/66992c832fe1c0aaa7f558ab9eb00027 to your computer and use it in GitHub Desktop.
Save jordancluts/66992c832fe1c0aaa7f558ab9eb00027 to your computer and use it in GitHub Desktop.
### A Pluto.jl notebook ###
function parse_line(line)
patterns, values = split.(split(line," | "),' ')
return collect.(patterns),collect.(values)
end
function Part1(file)
total = 0
uniques = Set([2,3,4,7])
for line in eachline(file)
patterns,values = parse_line(line)
l = length.(values)
c = count(x->(x in uniques),l)
total += c
end
return total
end
Part1("../Input/8.txt")
function DecodeLine(line)
#Split up line and convert to vectors of Sets
p, v = parse_line(line)
patterns = Set.(p)
values = Set.(v)
#Get lengths of all sets for later
lens = length.(patterns)
#Create Dict to store pairings
Decoder = Dict{Int,Set{Char}}()
#Pair up the easy ones
Decoder[1]=only(patterns[lens.==2])
Decoder[4]=only(patterns[lens.==4])
Decoder[7]=only(patterns[lens.==3])
Decoder[8]=only(patterns[lens.==7])
#Get the codes with 6 characters (numbers 0,6,9)
sixes = patterns[lens.==6]
# Only 9 contains the number 4 so can be identified and removed from consideration
Decoder[9] = only(filter(x->issubset(Decoder[4],x),sixes))
filter!(x->(x!=Decoder[9]),sixes)
#Only 0 contains the number 1 (after 9 removed)
Decoder[0] = only(filter(x->issubset(Decoder[1],x),sixes))
#6 is only remaining of length 6
Decoder[6] = only(filter(x->(x != Decoder[9] && x != Decoder[0]),sixes))
#Get the codes with 5 characters (numbers 2,3,5)
fives = patterns[lens.==5]
#Only 3 contains number 1
Decoder[3] = only(filter(x->issubset(Decoder[1],x),fives))
#Only 5 is contained by 6
Decoder[5] = only(filter(x->issubset(x,Decoder[6]),fives))
#2 is only remaining of length 5
Decoder[2] = only(filter(x->(x != Decoder[5] && x != Decoder[3]),fives))
#Create translator by reversing Decoder dict
Translator = Dict()
for (key,value) in pairs(Decoder)
Translator[value] = key
end
#Allocate output array
output = []
#lookup the number associated with each value
for k in values
push!(output,Translator[k])
end
#convert to integer
return output[1]*1000+output[2]*100+output[3]*10+output[4]
end
function Part2(file)
mapreduce(DecodeLine,+,eachline(file))
end
Part2("../Input/8.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment