Skip to content
advent of code 2015

day 08

matchsticks

approach

both directions are written by hand, one character at a time. decode walks the literal with an escape flag and a counter for the two digits of a hex escape, then drops the surrounding quotes. encode wraps the string in quotes and escapes every quote and backslash.

part 1 sums the difference between the literal length and the decoded length. part 2 sums the difference between the encoded length and the literal length.

the trick

a tiny state machine: one flag for a pending backslash, one counter for the hex digits still to read.

python
def encode(s):
    res = ['"']
    for c in s:
        if c == '"':
            res.append('\\"')
        elif c == "\\":
            res.append('\\\\')
        else:
            res.append(c)
    res.append('"')
    return "".join(res)