Sean McLemon | Advent of Code

Home | Czech | Blog | GitHub | Advent Of Code | Notes


2015-12-08 - Matchsticks

(original .ipynb)

Puzzle input is a sequence of escaped strings, surrounded by quotation marks. Part one involved unescaping the strings and finding out how many chars fewer there are when you do. Part two involves adding an extra layer of escaping on top of the input strings, and counting how many chars more there are now.

puzzle_input_str = open("./puzzle_input/day8.txt").read()

def unescape_string(string):
    string = string[1:][:-1]
    c = 0
    while c < len(string):

        if string[c] == "\\":
            if string[c+1] == "\\":
                yield "\\"
                c += 2
            elif string[c+1] == "\"":
                yield "\""
                c += 2
            elif string[c+1] == "x":
                yield chr(int(string[c+2:c+4], 16))
                c += 4
            else:
                raise Exception("escape code not supported")
        else:
            yield string[c]
            c += 1

            
def part_one(input_str):   
    extra_char_count = 0
    for raw_string in input_str.split("\n"):
        string = "".join(unescape_string(raw_string))
        extra_char_count += len(raw_string) - len(string)
    return extra_char_count


print("part one:", part_one(puzzle_input_str))
part one: 1371
def escape_string(string):
    c = 0
    to_escape = { "\\", "\"" }
    
    yield "\""
    while c < len(string):
        if string[c] in to_escape:
            yield "\\"
        yield string[c]
        c += 1
    yield "\""


def part_two(input_str):
    extra_char_count = 0
    for raw_string in input_str.split("\n"):
        string = "".join(escape_string(raw_string))
        extra_char_count += len(string) - len(raw_string)
    return extra_char_count


test_input_str = """\"\"
\"abc\"
\"aaa\\\"aaa\"
\"\\x27\""""


assert 19 == part_two(test_input_str)

print("part two:", part_two(puzzle_input_str))
part two: 2117