-
Notifications
You must be signed in to change notification settings - Fork 0
/
day9_2_ugly.py
55 lines (47 loc) · 1.25 KB
/
day9_2_ugly.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
import time
start_time = time.time()
is_test = False
day = 9
input_file = f'./input/day{day}{"_test" if is_test else ""}.txt'
long_str = open(input_file).readline().strip()
r = []
file_id = 0
dot_idx = []
id_idx = []
all_count = 0
for i, c in enumerate(long_str):
if i % 2:
for k in range(int(c)):
r.append('.')
dot_idx.append([all_count, int(c)])
all_count += int(c)
else:
for k in range(int(c)):
r.append(file_id)
id_idx.append([file_id, int(c)])
file_id += 1
all_count += int(c)
# print(r)
# optimize below
left, right = 0, len(r) - 1
right = len(r) - 1
while right > 0:
while r[right] == '.':
right -= 1
count = 1
while right > 0 and r[right] == r[right-1]:
right -= 1
count += 1
for i, (dot_index, l_dot) in enumerate(dot_idx):
if l_dot >= count and dot_index < right:
r[dot_index: count+dot_index], r[right:right+count] = r[right:right+count], r[dot_index: count+dot_index]
dot_idx[i] = [dot_index + count, l_dot - count]
break
right -= 1
# optimize above
total = 0
for i in range(len(r)):
if r[i] != '.':
total += i * r[i]
print(total)
print(f't2 = {time.time() - start_time:.6f}s')