Advent of Code: Day 13

For Day 13, the challenge is to figure out a safe path through some moving "scanners". My Python solution is below:

import itertools

layers = {}
max_depth = 0
with open("input.txt", "r") as o:
    for line in o.readlines():
        depth, r = line.strip().split(": ")
        layers[int(depth)] = int(r)
        max_depth = int(depth)

def check(layers, delay=0, return_early=False):
    depth = 0
    caught = []

    for picosecond in layers:
        if (picosecond + delay) % (2 * layers[picosecond] - 2) == 0:
            if return_early:
                return caught
    return caught

print "Part 1", sum([layers[d] * d for d in check(layers)])
print "Part 2", next(i for i in itertools.count() if len(check(layers, i, return_early=True)) == 0)

I struggled with this one until I realised the very simple modulus solution to figure out if it's safe to pass.

The second part is pretty slow and I think there will be a quicker way by calculating the safe numbers for each of the sensors individually rather than trying each delay.

Advent of Code runs every day up to Christmas, you should join in!.

Show Comments

Get the latest posts delivered right to your inbox.