60 lines
1.6 KiB
Julia
60 lines
1.6 KiB
Julia
include("utils.jl")
|
|
|
|
function parse_input(filename)
|
|
template, rawrules... = collect(non_empty_lines(filename))
|
|
rules = Dict()
|
|
for rule in rawrules
|
|
front, back = split(rule, " -> ")
|
|
first, second = split(front, "")
|
|
rules[[first[1], second[1]]] = back[1]
|
|
end
|
|
pairs = Dict()
|
|
for i in 1:length(template)-1
|
|
get!(pairs, [template[i], template[i+1]], 0)
|
|
pairs[[template[i], template[i+1]]] += 1
|
|
end
|
|
pairs, rules, [first(template), last(template)]
|
|
end
|
|
|
|
function countpoly(pairs, singles)
|
|
result = Dict()
|
|
for (key, value) in pairs
|
|
get!(result, key[1], 0)
|
|
result[key[1]] += value
|
|
get!(result, key[2], 0)
|
|
result[key[2]] += value
|
|
end
|
|
for single in singles
|
|
result[single] += 1
|
|
end
|
|
for key in keys(result)
|
|
result[key] = div(result[key], 2)
|
|
end
|
|
result
|
|
end
|
|
|
|
function solution14_2()
|
|
pairs, rules, singles = parse_input("14.data")
|
|
steps = 40
|
|
for step in 1:steps
|
|
new = Dict()
|
|
for (key, value) in pairs
|
|
insert = get!(rules, key, nothing)
|
|
if typeof(insert) == Char
|
|
get!(new, [key[1], insert], 0)
|
|
new[[key[1], insert]] += value
|
|
get!(new, [insert, key[2]], 0)
|
|
new[[insert, key[2]]] += value
|
|
else
|
|
get!(new, key, 0)
|
|
new[key] += value
|
|
end
|
|
end
|
|
pairs = new
|
|
end
|
|
counts = sort(collect(values(countpoly(pairs, singles))))
|
|
last(counts) - first(counts)
|
|
end
|
|
|
|
solution14_2()
|