Advertisement
Guest User

Untitled

a guest
Dec 11th, 2023
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 KB | None | 0 0
  1. import itertools
  2.  
  3.  
  4. def get_universe(file: str) -> list:
  5.     return open(file).read().splitlines()
  6.  
  7.  
  8. def get_vertical_expansions(universe: list):
  9.     amount = 0
  10.     for y in range(len(universe)):
  11.         for x in range(len(universe[0])):
  12.             if universe[y][x] == '#':
  13.                 break
  14.         else:
  15.             amount += 1
  16.  
  17.         yield amount
  18.  
  19.  
  20. def get_horizontal_espansions(universe: list):
  21.     amount = 0
  22.     for x in range(len(universe[0])):
  23.         for y in range(len(universe)):
  24.             if universe[y][x] == '#':
  25.                 break
  26.         else:
  27.             amount += 1
  28.  
  29.         yield amount
  30.  
  31.  
  32. def get_galaxies(universe: list):
  33.     for y in range(len(universe)):
  34.         for x in range(len(universe[0])):
  35.             if universe[y][x] == '#':
  36.                 yield x, y
  37.  
  38.  
  39. def adjusted_coordinate(expansion_factor: 1, coordinate: tuple, expansions_horizontal: tuple, expansions_vertical: tuple):
  40.     x, y = coordinate
  41.     return x + expansions_horizontal[x] * expansion_factor, y + expansions_vertical[y] * expansion_factor
  42.  
  43.  
  44. def manhattan_distance(coordinate_1: tuple, coordinate_2: tuple) -> int:
  45.     x1, y1 = coordinate_1
  46.     x2, y2 = coordinate_2
  47.  
  48.     return abs(x1 - x2) + abs(y1 - y2)
  49.  
  50.  
  51. def main(file: str, expansion_factor: int) -> int:
  52.     universe = get_universe(file)
  53.     expansions_horizontal = tuple(expansion for expansion in get_horizontal_espansions(universe))
  54.     expansions_vertical = tuple(expansion for expansion in get_vertical_expansions(universe))
  55.     coordinates = (coordinate for coordinate in get_galaxies(universe))
  56.  
  57.     coordinates_adjusted = (
  58.         adjusted_coordinate(
  59.             expansion_factor,
  60.             coordinate,
  61.             expansions_horizontal,
  62.             expansions_vertical
  63.         )
  64.         for coordinate in coordinates
  65.     )
  66.     distances = (
  67.         manhattan_distance(coordinate_1, coordinate_2)
  68.         for coordinate_1, coordinate_2 in itertools.combinations(coordinates_adjusted, 2)
  69.     )
  70.     return sum(distances)
  71.  
  72.  
  73. if __name__ == '__main__':
  74.     print('par1_1', main('input.txt', 1))
  75.     print('part_2', main('input.txt', 1_000_000 - 1))
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement