Advent of Code: Day 15

For Day 15, the challenge is to create some generators which follow particular rules for generating sequences, and then count the number of times the results match. My Python solution is below:

with open("input.txt", "r") as o:
    seed1 = int(o.readline().rsplit(" ", 1)[1])
    seed2 = int(o.readline().rsplit(" ", 1)[1])

FACTOR_A = 16807
FACTOR_B = 48271

DIVISION = 2147483647

def generator(previous, factor, multiples=1):
    while True:
        previous = (previous * factor) % DIVISION
        if previous % multiples == 0:
            yield previous

part1_generator1 = generator(seed1, FACTOR_A)
part1_generator2 = generator(seed2, FACTOR_B)

part2_generator1 = generator(seed1, FACTOR_A, 4)
part2_generator2 = generator(seed2, FACTOR_B, 8)

def count(generator1, generator2, n):
    return len([1 for _ in range(n) if generator1.next() & 0xffff == generator2.next() & 0xffff])

print "Part 1", count(part1_generator1, part1_generator2, 40000000)
print "Part 2", count(part2_generator1, part2_generator2, 5000000)

This uses Python generators which makes the solution pretty clean and easy to understand.

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

Show Comments

Get the latest posts delivered right to your inbox.