Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- from functools import reduce
- def manhattan_distance(a, b) -> int:
- return abs(a[0]-b[0])+abs(a[1]-b[1])
- if __name__ == "__main__":
- DATA_FILE = "galaxy.txt"
- with open(DATA_FILE) as data_file:
- # read data in
- lines = data_file.readlines()
- # remove line endings
- lines = [l.strip() for l in lines]
- # split into chars - 2D array - to numpy
- lines = np.array([[c for c in x] for x in lines])
- # get col and row indices where all '.'
- rows_idx=np.array(np.where(np.all(lines == ".", axis=1))).flatten()
- cols_idx=np.array(np.where(np.all(lines == ".", axis=0))).flatten()
- # add extra '.' rows and cols
- lines=np.insert(lines, rows_idx, '.', axis=0)
- lines=np.insert(lines, cols_idx, '.', axis=1)
- # get indices of the galaxies
- galaxy_idx = np.transpose((lines == '#').nonzero())
- # iterate through galaxy and calc distance
- 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)])
- # print the answer
- print(f"{total_distance}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement