advent-of-code/12021/14/14_2.awk

45 lines
861 B
Awk

BEGIN{ RS = "" }
NR==1{
template = $0
RS ="\n"
next
}
{ ins[$1] = $3 }
END{
# setup
for(i=1;i<length(template);i++){
p = substr(template,i,2)
paircount[p]++
}
# iterate
for(s=1;s<=40;s++){
delete newpaircount; delete countl; delete countr
for(p in paircount){
n = paircount[p]
c1 = substr(p,1,1)
c2 = substr(p,2,1)
toins = ins[p]
# print p, c1, toins, c2, n
newpaircount[c1 toins]+=n
newpaircount[toins c2]+=n
countl[c1]+=n
countr[toins]+=n
countl[toins]+=n
countr[c2]+=n
}
delete paircount
for(p in newpaircount) paircount[p] = newpaircount[p]
min = 999999999999
max = 0
for(c in countl){
count[c] = countl[c]>countr[c] ? countl[c] : countr[c]
if(count[c]>max) max=count[c]
if(count[c]<min) min=count[c]
}
if(s==10) print "part 1: ", max-min
if(s==40) print "part 2: ", max-min
}
}