Advent of Code 2015 Day 8

Author

Nathan Moore

— Day 8: Matchsticks —

Space on the sleigh is limited this year, and so Santa will be bringing his list as a digital copy. He needs to know how much space it will take up when stored.

Disregarding the whitespace in the file, what is the number of characters of code for string literals minus the number of characters in memory for the values of the strings in total for the entire file?

with open('data-2015-08.txt', 'r') as f:
    santa_list = f.read().splitlines()

Count each of the strings

sum(len(x) for x in santa_list)

sum(len(eval(x)) for x in santa_list)

sum(len(x) for x in santa_list) - sum(len(eval(x)) for x in santa_list)
1333

Let’s try a for loop for printing to see what’s happening. Does this make sense? It does.

for x in santa_list[:10]:
    print(str(len(x)) + ' ' + x)
    print(str(len(eval(x))) + ' ' + eval(x))
    
# 1333    
38 "sjdivfriyaaqa\xd2v\"k\"mpcu\"yyu\"en"
29 sjdivfriyaaqaÒv"k"mpcu"yyu"en
6 "vcqc"
4 vcqc
27 "zbcwgmbpijcxu\"yins\"sfxn"
23 zbcwgmbpijcxu"yins"sfxn
10 "yumngprx"
8 yumngprx
6 "bbdj"
4 bbdj
28 "czbggabkzo\"wsnw\"voklp\"s"
23 czbggabkzo"wsnw"voklp"s
6 "acwt"
4 acwt
36 "aqttwnsohbzian\"evtllfxwkog\"cunzw"
32 aqttwnsohbzian"evtllfxwkog"cunzw
9 "ugvsgfv"
7 ugvsgfv
12 "xlnillibxg"
10 xlnillibxg

— Part Two —

Go the other way, expand things.

Your task is to find the total number of characters to represent the newly encoded strings minus the number of characters of code in each original string literal.

This looks like we have to find the required characters: \ + " + 2 for each string, quotes at the start and end.

nn = 0

for x in santa_list:
    nn += sum(1 for y in x if '\\' in y)
    nn += sum(1 for y in x if '"' in y)
    nn += 2

nn

# 2046
2046