Advent of Code: Day #09 - Encoding Error
4 minutes
Introduction
We're breaking the eXchange-Masking Addition System (XMAS - Wow I only just got that joke, that's awful) today!
Task One
The XMAS encryption algorithm sends 25 numbers before the data starts. Every number after that must be equal to the sum of any two of the previous 25 numbers. We're tasked with finding the first number that is not valid.
Reading in the data
Today I just read each number into an array.
def read_data(path):dataset = []with open(path, 'r') as f:for line in f.readlines():dataset.append(int(line))return dataset
The Solution
I used the combinations function form itertools to genetrate every 2 digit pair of the last 25 numbers and then took the sum of them. Then it's as simple as chekcing if current number is in this list, if it's not we return it.
def task_one(numbers, p_size=25):for i, n in enumerate(numbers[p_size:]):possibilities = [sum(group) for group incombinations(numbers[i:i + p_size], 2)]if n not in possibilities:return n
Task Two
The Solution
For task two we must find a contiguous set of numbers that sum to the invalid number we found in part one. I took a brute force approach to this and generated every combination and check if they sum to the invalid number.
def task_two(numbers, invalid):for i in range(len(numbers)):for j in range(i + 2, len(numbers)):if sum(numbers[i:j]) == invalid:return min(numbers[i:j]) + max(numbers[i:j])
Golf Solution
A super small condensed version of the code.
from itertools import combinationsd = [int(i) for i in open("input.txt").read().split("\n")]print([n for i, n in enumerate(d[25:]) if n not in [sum(g) for g in combinations(d[i:i + 25], 2)]][0])print([min(d[i:j]) + max(d[i:j]) for i in range(len(d)) for j in range(i + 2, len(d)) if sum(d[i:j]) == 2089807806][0])
Links
Leaderboard Code: 353270-1fc6ef28
Github Repository A link to the github repo containing all the days.
main.py A direct download of the main.py script
1.1Kb