Source: Inverse Captcha
Part 1: Given a number, what is the sum of pairs of digits that match (wrapping the last digit around to the first)?
Using my library functions, this is as easy as looping across each number and using zip
to iterate over pairs:
for line in lib.input():
total = 0
for c1, c2 in zip(line, line[1:] + line[:1]):
if c1 == c2:
total += int(c1)
print(total)
Part 2: Rather than considering adjacent pairs, pair each number with the number halfway around the list. What is the sum of matching pairs this time?
This time, we use the math
function from lib.py and a new function to calculate the offset:
lib.add_argument('--function', default = '1', help = 'Function for offset, variables: size')
for line in lib.input():
total = 0
offset = lib.math(lib.param('function'), {'size': len(line)})
for c1, c2 in zip(line, line[offset:] + line[:offset]):
if c1 == c2:
total += int(c1)
print(total)
Using this, part 1 can be run as:
$ python3 ahctpat.py input.txt
$ python3 ahctpat.py input.txt --function "1"
And part 2 is:
$ python3 ahctpat.py input.txt --function "size // 2"
Neat.
Runtimes using run-all.py:
$ python3 run-all.py day-01
day-01 python3 ahctpat.py input.txt 0.06595706939697266 1102
day-01 python3 ahctpat.py input.txt --function "size // 2" 0.05970120429992676 1076