blob: 3a3e1e6722d85268b6a27f0ab469924e2e424409 (
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#advent of code 2024
#day 09 - part 1
#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
part1 = 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;
si = 0; #space index
fi = fid -1; #file index
originalSize = len(files[fi]);
while sum([len(freespace[x]) for x in freespace]) > 0:
#empty list of freespaces - change to another one
if len(freespace[si]) == 0:
si += 1;
continue;
#clear freespace that is after the fileblock with biggest index
FileMax = max([max(files[x]) for x in files]);
if FileMax < freespace[si][-1]:
freespace[si].pop(-1);
continue;
#switch places between last fileblock and first freespace
files[fi].pop();
originalSize -= 1;
NewSpace = freespace[si].pop(0);
files[fi].insert(0,NewSpace);
#if that was the last fileblock, switch to second to last file
if originalSize == 0:
fi -= 1;
originalSize = len(files[fi]);
#checksum calculation
for file in files:
for f in files[file]:
part1 += file*f;
print("part 1 =", part1);
|