Advertisement
Fermi-4

Day 11 Part 1

Dec 11th, 2023
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. import numpy as np
  2. from functools import reduce
  3.  
  4. def manhattan_distance(a, b) -> int:
  5.     return abs(a[0]-b[0])+abs(a[1]-b[1])
  6.  
  7. if __name__ == "__main__":
  8.  
  9.     DATA_FILE = "galaxy.txt"
  10.     with open(DATA_FILE) as data_file:
  11.  
  12.         # read data in
  13.         lines = data_file.readlines()
  14.  
  15.         # remove line endings
  16.         lines = [l.strip() for l in lines]
  17.  
  18.         # split into chars - 2D array - to numpy
  19.         lines = np.array([[c for c in x] for x in lines])
  20.  
  21.         # get col and row indices where all '.'
  22.         rows_idx=np.array(np.where(np.all(lines == ".", axis=1))).flatten()
  23.         cols_idx=np.array(np.where(np.all(lines == ".", axis=0))).flatten()
  24.    
  25.         # add extra '.' rows and cols
  26.         lines=np.insert(lines, rows_idx, '.', axis=0)
  27.         lines=np.insert(lines, cols_idx, '.', axis=1)
  28.        
  29.         # get indices of the galaxies
  30.         galaxy_idx = np.transpose((lines == '#').nonzero())
  31.        
  32.         # iterate through galaxy and calc distance
  33.         total_distance = reduce(lambda x,y: np.sum(x)+np.sum(y), [np.array([manhattan_distance(galaxy_idx[i], galaxy_idx[j]) for j in range(i+1, len(galaxy_idx))]) for i in range(len(galaxy_idx)-1)])
  34.  
  35.         # print the answer
  36.         print(f"{total_distance}")
  37.        
  38.  
  39.  
  40.  
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement