Advertisement
Guest User

AOC 2021 Day 7

a guest
Dec 9th, 2021
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. # aoc202107.py
  2.  
  3. # Refactor - this is very slow
  4.  
  5. import pathlib
  6. import sys
  7.  
  8.  
  9. def parse(puzzle_input: str) -> list[int]:
  10.     """ Parse input """
  11.     return [int(n) for n in puzzle_input.split(',')]
  12.  
  13.  
  14. def calc_cost(target: int, positions: list[int]) -> int:
  15.     """ Calculate the sum of the differences between target and items in positions """
  16.     cost = 0
  17.     for pos in positions:
  18.         cost += abs(target - pos)
  19.     return cost
  20.  
  21.  
  22. def triangular(num: int) -> int:
  23.     """ Return the triangular number for num """
  24.     return (num * (num + 1)) // 2
  25.  
  26.  
  27. def calc_new_cost(target: int, positions: list[int]) -> int:
  28.     """ Calculate the sum of the differences between target and items in positions """
  29.     cost = 0
  30.     for pos in positions:
  31.         diff = abs(target - pos)
  32.         cost += triangular(diff)
  33.     return cost
  34.  
  35.  
  36. def part1(data: list[int]) -> int:
  37.     """ Solve part 1 """
  38.     freq_positions = range(min(data), max(data))
  39.     return min(calc_cost(n, data) for n in freq_positions)
  40.  
  41.  
  42. def part2(data: list[int]) -> int:
  43.     """ Solve part 2 """
  44.     freq_positions = range(min(data), max(data))
  45.     return min(calc_new_cost(n, data) for n in freq_positions)
  46.  
  47.  
  48. def solve(puzzle_input: str) -> tuple[int, int]:
  49.     """ Solve the puzzle for the given input """
  50.     data = parse(puzzle_input)
  51.     solution1 = part1(data)  # Correct answer was 336721 (with my data)
  52.     solution2 = part2(data)  # Correct answer was 91638945 (with my data)
  53.  
  54.     return solution1, solution2
  55.  
  56.  
  57. if __name__ == "__main__":
  58.     for path in sys.argv[1:]:
  59.         print(f"{path}:")
  60.         puzzle_input = pathlib.Path(path).read_text().strip()
  61.         solutions = solve(puzzle_input)
  62.         print('\n'.join(str(solution) for solution in solutions))
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement