day 05
alchemical reduction
approach
the polymer is a string. reduce scans it with an index: when two neighbours are the same letter in different cases (their character codes differ by exactly 32) it cuts both out and steps back one place, since the removal may have brought a new pair together; otherwise it moves forward.
part 1 is the length after reducing. part 2 removes each letter A–Z (both cases) from the original, reduces what's left, and takes the shortest result.
the trick
after removing a pair, step back one position instead of restarting, so the scan stays a single pass.
python
def reduce(before):
i=0
res=before
while i<len(res)-1:
if abs(ord(res[i])-ord(res[i+1]))==32:
res=(res[:i]+res[i+2:])
i-=1
if i<0:
i=0
else:
i+=1
return res