Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- with open("day9input.txt") as f:
- input_nums = [int(x) for x in f.read()]
- len_input = len(input_nums)
- file_sizes = input_nums[0:len_input:2]
- empty_spaces = input_nums[1:len_input:2]
- # construct the disk representation of the input
- # store all the files / empty space ranges for later
- disk_representation = []
- file_ranges = []
- empty_ranges = []
- for idx in range(len(file_sizes)):
- left = len(disk_representation)
- disk_representation += [idx] * file_sizes[idx]
- right = len(disk_representation)-1
- file_ranges.append([left, right])
- if idx < len(empty_spaces):
- left = len(disk_representation)
- disk_representation += ['.'] * empty_spaces[idx]
- right = len(disk_representation)-1
- if empty_spaces[idx] > 0:
- empty_ranges.append([left, right])
- curr_file_id = len(file_sizes) - 1
- # once for each file, start looking for a large enough empty space from the beginning of the disk
- while curr_file_id > 0:
- curr_file_size = file_ranges[curr_file_id][1] - file_ranges[curr_file_id][0] + 1
- for empty in empty_ranges:
- if empty[0] > file_ranges[curr_file_id][0]:
- # break out of the loop if the empty space isn't to the left of the file
- break
- if curr_file_size <= empty[1] - empty[0] + 1:
- # space found. right_idx is the rightmost index of the file in the disk representation
- # left_idx is the leftmost index of the empty space
- right_idx = file_ranges[curr_file_id][1]
- left_idx = empty[0]
- for _ in range(curr_file_size):
- # looks a little wonky, but this just swaps the values at left_idx and right_idx
- (disk_representation[left_idx],
- disk_representation[right_idx]) = (disk_representation[right_idx],
- disk_representation[left_idx])
- right_idx -= 1
- left_idx += 1
- empty[0] += curr_file_size
- break
- curr_file_id -= 1
- # count up the output, ignoring empty space
- output = 0
- for idx in range(len(disk_representation)):
- if disk_representation[idx] != '.':
- output += disk_representation[idx] * idx
- print(output)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement