Advent of Code: Day 17

For Day 17, the challenge is to repeatedly insert numbers into a list following some specific rules, and then find the position of a given number. My Python solution is below:

with open("input.txt", "r") as o:
    steps = int(o.read())

def spinlock(max_number, target):
    l = [0]
    ptr = 0

    for i in range(1, max_number + 1):
        ptr = ((ptr + steps) % len(l)) + 1
        l.insert(ptr, i)

    return l[l.index(target) + 1]

def spinlock_zero(max_number):
    ptr = 0
    following_zero = None

    for i in range(1, max_number + 1):
        ptr = ((ptr + steps) % i) + 1
        if ptr == 1:
            following_zero = i

    return following_zero

print "Part 1", spinlock(2017, 2017)
print "Part 2", spinlock_zero(50000000)

Part 2 is optimised because I realised that zero will never move from the first position - so there's no need to waste time maintaining a list of 50million integers - we can just track any that get inserted immediately after zero.

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

Show Comments

Get the latest posts delivered right to your inbox.