diff --git a/2024/09/part2.py b/2024/09/part2.py index 2ceeb8e..163c3ed 100644 --- a/2024/09/part2.py +++ b/2024/09/part2.py @@ -12,7 +12,7 @@ def disk_map_to_files(disk_map: str) -> list: files += [int(s) * [str(ID)]] # free space - else: + elif int(s) > 0: files += [int(s) * "."] return files @@ -21,28 +21,40 @@ def move_files_ltr_to_empty_space(files: list) -> str: left = 0 right = len(files) - 1 - while left < right: + while 0 < right: + #print(files) + #print(left, right) + + # Concatenate empty space + while "." in files[left] and "." in files[left + 1]: + files[left] += files[left + 1] + del(files[left + 1]) + right -= 1 + + if not left < right: + right -= 1 + left = 0 + continue + if not "." in files[left]: #print("if ", end=" ") left += 1 - # TODO: Shouldn't we take care of this in the partial block? - elif len(files[right]) == 0: - del(files[right]) - elif "." in files[right] \ - or files[left].count(".") < len(files[right]): + elif "." in files[right]: right -= 1 #print("elif", end=" ") + elif files[left].count(".") < len(files[right]): + left += 1 + continue # fully swap elif files[left].count(".") == len(files[right]): - #print("part", end=" ") + #print("full", end=" ") tmp = files[left] files[left] = files[right] files[right] = tmp - # Restart trying from the right - right = len(files) - 1 - - # TODO: Concatenate empty space + # Restart trying from the left + left = 0 + right -= 1 # partially swap else: #print("part", end=" ") @@ -55,13 +67,14 @@ def move_files_ltr_to_empty_space(files: list) -> str: files.insert(left + 1, tmp[:-len(files[right])]) idx_right_after_insertion = right + 1 files[idx_right_after_insertion] = tmp[:len(files[idx_right_after_insertion])] - if len(files[idx_right_after_insertion]) == 0: - #print("deleting") + if len(files[right]) == 0: del(files[idx_right_after_insertion]) + right -= 1 #print("RIGHT: ", files[right]) - # Restart trying from the right - right = len(files) - 1 + # Restart trying from the left + left = 0 + if verbose: print(files_to_blocks(files))