-
Notifications
You must be signed in to change notification settings - Fork 0
/
day9.py
84 lines (67 loc) · 2.72 KB
/
day9.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
"""--- Day 9: Explosives in Cyberspace ---"""
FILE = 'input.txt'
DEBUG_INPUT = "(3x3)XYZ\nX(8x2)(3x3)ABCY\n(27x12)(20x12)(13x14)(7x10)(1x12)A"
DEBUG = False
import re
def init(file):
with open(file) as f:
input = f.read()
return input
def decompress(line):
uncompressed = ""
it = re.finditer(r'\(([0-9]+x[0-9]+)\)', line)
start = 0
for patt in it:
if start > patt.start(): # previous iteration went over this marker
continue
uncompressed += line[start:patt.start()]
numbers = patt.group(1).split('x')
str_len_to_unc = numbers[0]
times_to_unc = numbers[1]
uncompressed += line[patt.end():patt.end() + int(str_len_to_unc)] * int(times_to_unc)
start = patt.end() + int(str_len_to_unc)
uncompressed += line[start:] # add trailing chars in line
return uncompressed
def decompress_markers(line):
uncompressed = ""
it = re.finditer(r'\(([0-9]+x[0-9]+)\)', line)
start = 0
for patt in it:
if start > patt.start(): # previous iteration went over this marker
continue
uncompressed += line[start:patt.start()]
numbers = patt.group(1).split('x')
str_len_to_unc = numbers[0]
times_to_unc = numbers[1]
uncompressed += decompress_markers(line[patt.end():patt.end() + int(str_len_to_unc)]) * int(times_to_unc)
start = patt.end() + int(str_len_to_unc)
uncompressed += line[start:] # add trailing chars in line
return uncompressed
def decompress_markers_length(line):
uncompressed_length = 0
it = re.finditer(r'\(([0-9]+x[0-9]+)\)', line)
start = 0
for patt in it:
if start > patt.start(): # previous iteration went over this marker
continue
if start < patt.start():
uncompressed_length += decompress_markers_length(line[start:patt.start()]) # /!\ I was skipping this. If the new pattern is further than the previous uncompression length
numbers = patt.group(1).split('x')
str_len_to_unc = numbers[0]
times_to_unc = numbers[1]
uncompressed_length += decompress_markers_length(line[patt.end():patt.end() + int(str_len_to_unc)]) * int(times_to_unc)
start = patt.end() + int(str_len_to_unc)
uncompressed_length += len(line[start:]) # add trailing chars in line
return uncompressed_length
if __name__ == '__main__':
if DEBUG:
inputd = DEBUG_INPUT
else:
inputd = init(FILE)
inputd_lines = inputd.splitlines()
decompressed_length = 0
for line in inputd_lines:
decompressed_length += decompress_markers_length(line)
#print(decompress_markers(line))
print("Decompressed length is " + str(decompressed_length))