Day 8, Year 2015: Matchsticks
First read the problem description.
from enum import Enum, auto
class State(Enum):
= auto()
StartString = auto()
ParseString = auto()
EscapeCharacter = auto()
EscapeHexadecimal
def count_characters(s):
= 0
cc = 0
cm = 0
ce = State.StartString
state
= 0
hexadecimal_count
for i in range(len(s)):
if s[i].isspace():
continue
+= 1
cc += 1
ce
if s[i] in ('"', '\\'):
+= 1
ce
if state is State.StartString:
if s[i] != '"':
raise Exception('expecting "')
+= 2
ce = State.ParseString
state continue
if state is State.ParseString:
if s[i] == '\\':
= State.EscapeCharacter
state continue
if s[i] == '"':
= State.StartString
state continue
+= 1
cm
if state is State.EscapeCharacter:
if s[i] == 'x':
= State.EscapeHexadecimal
state = 0
hexadecimal_count continue
else:
= State.ParseString
state += 1
cm
if state is State.EscapeHexadecimal:
+= 1
hexadecimal_count
if hexadecimal_count == 2:
= State.ParseString
state += 1
cm
return cc, cm, ce
import import_ipynb
import helper
= helper.read_file('2015_8.txt') s
= count_characters(s)
cc, cm, ce print(cc - cm)
print(ce - cc)
1371
2117
Source code of the solution(s):