Advent of Code 2020 – Day 9
The puzzle for Day 9 ended up being fairly easy. It’s basically striding across some arrays for values. The task was to decrypt a fake code set by exploiting a known bug. Sounds fancy, but that’s just the story for the day, there isn’t any real complex hacking going on here or anything.
What you get is a string of numbers output from the device, to find the “exploit” you have to find the first number that doesn’t fit the pattern. The pattern being that each number (after a preamble set of numbers) is the sum of two of the previous numbers, within a range.
with open('day9data.txt') as f:
lines = [line.rstrip() for line in f]
position = 25
while(True):
valid_nums=lines[position-25:position]
valid = 0
current = int(lines[position])
print current
for i in valid_nums:
check = current - int(i)
#print str(current) +"-"+ i +"="+str(check)
if str(check) in valid_nums:
#print check
valid=1
print valid
if valid == 1:
print position
position+=1
else:
print current
break
So for Part 1, read in the code, set the starting position of 25 (for the 25 number preamble), then take the 26th number, then run some loops across the previous 25 numbers, adding each number to each other number, until you find the 26th number. If it works, move on tot he next number, until it doesn’t.
Part two, is to execute the “exploit” by finding a continuous set of numbers, that add up to the result of the first set of numbers. For the sake of keeping the code universally useful, Part 1 gets run again to find the key value.
After wards, it’s more loops adding up numbers. Start at the first value, start adding until the sum is greater than the key value, then reset, and start again at the next number. Until the sum equal the exploit value. Then return the result, which in this case was the sum of the first and last number int he continuous run of numbers.
with open('day9data.txt') as f:
lines = [line.rstrip() for line in f]
position = 25
while(True):
valid_nums=lines[position-25:position]
valid = 0
current = int(lines[position])
#print current
for i in valid_nums:
check = current - int(i)
#print str(current) +"-"+ i +"="+str(check)
if str(check) in valid_nums:
#print check
valid=1
#print valid
if valid == 1:
#print position
position+=1
else:
break
print current
start=0
position=start
total=0
sum_array=[]
while(total != current):
if total < current:
total+=int(lines[position])
position+=1
#print total
else:
start+=1
position=start
total=0
for i in lines[start:position]:
sum_array.append(int(i))
sum_array = sorted(sum_array)
print sum_array
print int(sum_array[0])+int(sum_array[-1])
There may be a quicker way to find these value but just straight brute forcing it on both fronts works pretty well.
Josh Miller aka “Ramen Junkie”. I write about my various hobbies here. Mostly coding, photography, and music. Sometimes I just write about life in general. I also post sometimes about toy collecting and video games at Lameazoid.com.