Advent of Code: Day 9

For Day 9, the challenge is to parse a stream of text and counting occurences of certain patterns. Heres my Python solution:

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

index = 0
current_score = 0
current_depth = 0
garbage_count = 0

def read():
    global index
    if data[index] == "!":
        index += 2
        return read()
    d = data[index]
    index += 1
    return d

def read_garbage():
    global index
    global garbage_count
    next_char = read()
    while not next_char == ">":
        garbage_count += 1
        next_char = read()

def start_group():
    global current_depth
    current_depth += 1

def end_group():
    global current_score
    global current_depth
    current_score += current_depth
    current_depth -= 1

while index < len(data):
    next_char = read()
    if next_char == "{":
        start_group()
    elif next_char == "}":
        end_group()
    elif next_char == "<":
        read_garbage()
    elif next_char == ",":
        pass # Skip commas
    else:
        print "Unknown character: ", next_char

print "Part 1:", current_score
print "Part 2:", garbage_count

I think this could be done with a regex, but that would have taken me a lot longer to write and would be near unreadable. This is simple, fast, and gets the right solution.

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

Show Comments

Get the latest posts delivered right to your inbox.