Advent of Code: Day 10


Part 1: Repeat a Look-and-say sequence 40 times. Return the length.

def look_and_say(seq):
    result = ''
    index = 0
    count = 0
    buffer = None

    for c in seq:
        if c == buffer:
            count += 1
            if buffer:
                result += '{}{}'.format(count, buffer)
            count = 1
            buffer = c

    result += '{}{}'.format(count, buffer)
    return result

def repeat(f, n, seq):
    for i in range(n):
        seq = f(seq)
    return seq

print(len(repeat(look_and_say, int(sys.argv[2]), sys.argv[1])))

I’ve already gone into far more detail on Look and Say sequences before. But this time, we’re doing it iteratively in Python! Basically, we just maintain a bit of state for which character we are currently counting. When we change, output; otherwise, incrememnt the change.

There are some interesting tricks you could do with regular expressions, but I doubt you can find something faster or much more elegant than this.

Part 2: Repeat 50 times.

There’s nothing particular interesting about this one. I’ve already accounted for this by passing in the second paramter on the command line.