Advertisement
CrayonCrayoff

AoC 2024 Day 9 part 2

Dec 10th, 2024 (edited)
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. with open("day9input.txt") as f:
  2.     input_nums = [int(x) for x in f.read()]
  3.  
  4. len_input = len(input_nums)
  5.  
  6. file_sizes = input_nums[0:len_input:2]
  7. empty_spaces = input_nums[1:len_input:2]
  8.  
  9.  
  10. # construct the disk representation of the input
  11. # store all the files / empty space ranges for later
  12. disk_representation = []
  13. file_ranges = []
  14. empty_ranges = []
  15. for idx in range(len(file_sizes)):
  16.     left = len(disk_representation)
  17.     disk_representation += [idx] * file_sizes[idx]
  18.     right = len(disk_representation)-1
  19.     file_ranges.append([left, right])
  20.     if idx < len(empty_spaces):
  21.         left = len(disk_representation)
  22.         disk_representation += ['.'] * empty_spaces[idx]
  23.         right = len(disk_representation)-1
  24.         if empty_spaces[idx] > 0:
  25.             empty_ranges.append([left, right])
  26.  
  27. curr_file_id = len(file_sizes) - 1
  28. # once for each file, start looking for a large enough empty space from the beginning of the disk
  29. while curr_file_id > 0:
  30.     curr_file_size = file_ranges[curr_file_id][1] - file_ranges[curr_file_id][0] + 1
  31.     for empty in empty_ranges:
  32.         if empty[0] > file_ranges[curr_file_id][0]:
  33.             # break out of the loop if the empty space isn't to the left of the file
  34.             break
  35.         if curr_file_size <= empty[1] - empty[0] + 1:
  36.             # space found. right_idx is the rightmost index of the file in the disk representation
  37.             # left_idx is the leftmost index of the empty space
  38.             right_idx = file_ranges[curr_file_id][1]
  39.             left_idx = empty[0]
  40.             for _ in range(curr_file_size):
  41.                 # looks a little wonky, but this just swaps the values at left_idx and right_idx
  42.                 (disk_representation[left_idx],
  43.                  disk_representation[right_idx]) = (disk_representation[right_idx],
  44.                                                     disk_representation[left_idx])
  45.                 right_idx -= 1
  46.                 left_idx += 1
  47.             empty[0] += curr_file_size
  48.             break
  49.     curr_file_id -= 1
  50.  
  51.  
  52. # count up the output, ignoring empty space
  53. output = 0
  54. for idx in range(len(disk_representation)):
  55.     if disk_representation[idx] != '.':
  56.         output += disk_representation[idx] * idx
  57. print(output)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement