From 4d32df27b034fe0cf1014383f4a930a1678e3e4f Mon Sep 17 00:00:00 2001 From: Luc Rubio Date: Tue, 10 Dec 2024 00:53:48 +0100 Subject: [PATCH] AoC 2024.9.2 fix pesky bug --- aoc2024/src/day09/python/solution.py | 16 ++++++++-------- aoc2024/test/day09/python/test_solution.py | 5 +---- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/aoc2024/src/day09/python/solution.py b/aoc2024/src/day09/python/solution.py index 4c97994..c2256b8 100644 --- a/aoc2024/src/day09/python/solution.py +++ b/aoc2024/src/day09/python/solution.py @@ -78,12 +78,13 @@ def _defrag_whole_files(disk_map: str, disk: list[str]) -> list[str]: try: file_start_index = disk.index(str(file_id)) free_space_index = _find_first_available_space(disk, file_start_index, file_size) - # Clear from previous location. - for i in range(file_start_index, file_start_index + file_size): - disk[i] = _EMPTY_SPACE - # Move to empty space. - for i in range(free_space_index, free_space_index + file_size): - disk[i] = str(file_id) + if free_space_index < file_start_index: + # Clear from previous location. + for i in range(file_start_index, file_start_index + file_size): + disk[i] = _EMPTY_SPACE + # Move to empty space. + for i in range(free_space_index, free_space_index + file_size): + disk[i] = str(file_id) except SpaceNotFoundError: # Skip file IDs with size zero. # Only attempt to move file once. @@ -102,8 +103,7 @@ def _checksum(disk: list[str], move_whole_files) -> int: if move_whole_files: # Need to scan the whole disk. # There can be empty space between files. - return sum(index * int(file_id) if file_id != _EMPTY_SPACE else 0 - for index, file_id in enumerate(disk)) + return sum(i * int(val) for i, val in enumerate(disk) if val.isdigit()) else: for index, value in enumerate(disk): # Disk is organized so we can stop here. No need to scan whole disk. diff --git a/aoc2024/test/day09/python/test_solution.py b/aoc2024/test/day09/python/test_solution.py index 7c58127..d7e5e59 100644 --- a/aoc2024/test/day09/python/test_solution.py +++ b/aoc2024/test/day09/python/test_solution.py @@ -37,10 +37,7 @@ def test_part2_withExample2_checksums(self): self.assertEqual(2858, checksum('2333133121414131402', move_whole_files=True)) def test_part2_withPuzzleInput_checksums(self): - # 2829791 too low. - # 12337449353604 too high. - # 6476727100241 too high. - self.assertEqual(999, checksum(self.input, move_whole_files=True)) + self.assertEqual(6476642796832, checksum(self.input, move_whole_files=True)) if __name__ == '__main__':