summaryrefslogtreecommitdiff
path: root/2024/aoc2024-d09-2.py
blob: 483388ef8029a824065cc596610c3e8a3239fb0c (plain)
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
#advent of code 2024
#day 09 - part 2
#I'll rewrite it to include both parts in the same file one day
#tbh I'm not even reviewing this shit
#very slow part 1, part 2 relatively fast

part2 = 0;
disk = open("09.in","r").readline().strip();
files = {};
freespace = {};
NewDisk = {};
fid = 0;
sid = 0;
ind = 0;
for i in range (0,len(disk)):
	if i%2 == 0:
		files[fid] =[int(x)+ind for x in range(int(disk[i]))];
		ind += int(disk[i]);
		fid += 1;
	else:
		freespace[sid] = [int(x)+ind for x in range(int(disk[i]))];
		ind += int(disk[i]);
		sid +=1;
	
for fi in range(fid-1,-1,-1): #file index, from last to first
	CurrentLimit = min(files[fi]);
	for si in range(0, len(freespace)): #space index, from first to last
		if len(freespace[si]) <= 0: continue;
		if max(freespace[si]) > CurrentLimit: break;
		if len(freespace[si]) >= len(files[fi]):
			OriginalSize = 0 + len(files[fi]);
			for o in range(OriginalSize):
				files[fi].pop();
				NewSpace = freespace[si].pop(0);
				files[fi].insert(0,NewSpace);
			break;

for file in files:
	for f in files[file]:
		part2 += file*f;
print("part 2 =", part2);