AdventOfCode/2024/09/solution.py

131 lines
4.0 KiB
Python

#!/bin/python3
import sys,time,re
from pprint import pprint
sys.path.insert(0, '../../')
from fred import list2int,get_re,nprint,lprint,loadFile
start_time = time.time()
input_f = 'input'
part = 2
def createMap(diskmap):
for i in range(len(instructions)):
t = []
if i%2 == 0:
for x in range(instructions[i]):
t.append(int(i/2))
else:
for x in range(instructions[i]):
t.append('')
diskmap.append(t)
return diskmap
#########################################
# #
# Part 1 #
# #
#########################################
if part == 1:
print("--- Loading File ---")
instructions = list2int(list(loadFile(input_f)[0]))
print(" %s seconds ---" % (time.time() - start_time))
diskmap = createMap([])
print("--- Creating Map ---")
print(" %s seconds ---" % (time.time() - start_time))
for i in range(len(diskmap)):
if i%2!=0:
try:
if len(diskmap[i]) > 0:
for x in range(len(diskmap[i])):
if (len(diskmap[-1])) > 0:
diskmap[i][x] = diskmap[-1].pop()
while diskmap[-1] == [] or diskmap[-1] == [''] or diskmap[-1][0] == '':
diskmap.pop()
except:
break
numbers = []
for j in range(len(diskmap)):
for i in range(len(diskmap[j])):
numbers.append(diskmap[j][i])
result = 0
for idx,i in enumerate(numbers):
result += (idx*i)
print("--- Calculating Part 1 ---")
print(result)
print(" %s seconds ---" % (time.time() - start_time))
#########################################
# #
# Part 2 #
# #
#########################################
if part == 2:
print("--- Loading File ---")
instructions = list2int(list(loadFile(input_f)[0]))
print(" %s seconds ---" % (time.time() - start_time))
diskmap = createMap([])
print("--- Creating Map ---")
print(" %s seconds ---" % (time.time() - start_time))
def split_list(input_list):
digits = [x for x in input_list if x != '']
empties = [x for x in input_list if x == '']
if not empties:
return [digits]
elif digits:
return [digits, empties]
diskmap = [sublist for sublist in diskmap if sublist != []]
for i in range(len(diskmap)):
if '' in diskmap[i]:
solved = False
if len(diskmap[i]) > 0:
offset = 0
while not solved:
if len(diskmap[i]) >= len(diskmap[-(1+offset)]) and diskmap[-(1+offset)][0] != '':
for x in range(len(diskmap[-(1+offset)])):
if (len(diskmap[-(1+offset)])) > 0:
diskmap[i][x] = diskmap[-(1+offset)][x]
diskmap[-(1+offset)][x] = ''
diskmap = diskmap[:i] + split_list(diskmap[i]) + diskmap[i+1:]
solved = True
elif i < len(diskmap)-offset-2:
offset += 1
else:
solved = True
elif diskmap[i] == []:
diskmap.remove(i)
numbers = []
for j in range(len(diskmap)):
for i in range(len(diskmap[j])):
t = diskmap[j][i]
if t == '':
numbers.append(0)
else:
numbers.append(t)
result = 0
for idx,i in enumerate(numbers):
result += (idx*i)
print("--- Calculating Part 1 ---")
print(result)
print(" %s seconds ---" % (time.time() - start_time))