Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # aoc202107.py
- # Refactor - this is very slow
- import pathlib
- import sys
- def parse(puzzle_input: str) -> list[int]:
- """ Parse input """
- return [int(n) for n in puzzle_input.split(',')]
- def calc_cost(target: int, positions: list[int]) -> int:
- """ Calculate the sum of the differences between target and items in positions """
- cost = 0
- for pos in positions:
- cost += abs(target - pos)
- return cost
- def triangular(num: int) -> int:
- """ Return the triangular number for num """
- return (num * (num + 1)) // 2
- def calc_new_cost(target: int, positions: list[int]) -> int:
- """ Calculate the sum of the differences between target and items in positions """
- cost = 0
- for pos in positions:
- diff = abs(target - pos)
- cost += triangular(diff)
- return cost
- def part1(data: list[int]) -> int:
- """ Solve part 1 """
- freq_positions = range(min(data), max(data))
- return min(calc_cost(n, data) for n in freq_positions)
- def part2(data: list[int]) -> int:
- """ Solve part 2 """
- freq_positions = range(min(data), max(data))
- return min(calc_new_cost(n, data) for n in freq_positions)
- def solve(puzzle_input: str) -> tuple[int, int]:
- """ Solve the puzzle for the given input """
- data = parse(puzzle_input)
- solution1 = part1(data) # Correct answer was 336721 (with my data)
- solution2 = part2(data) # Correct answer was 91638945 (with my data)
- return solution1, solution2
- if __name__ == "__main__":
- for path in sys.argv[1:]:
- print(f"{path}:")
- puzzle_input = pathlib.Path(path).read_text().strip()
- solutions = solve(puzzle_input)
- print('\n'.join(str(solution) for solution in solutions))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement