Created
December 11, 2018 05:52
-
-
Save leepike/750066beae02bb43db882131e62fa88e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
filepath = "input.txt" | |
def max_bounds(pts): | |
max_x = 0 | |
max_y = 0 | |
for x, y in pts: | |
if x > max_x: max_x = x | |
if y > max_y: max_y = y | |
return (x,y) | |
def mk_pairs(lines): | |
for idx, l in enumerate(lines): | |
xy = l.split(',') | |
lines[idx] = (int(xy[0]), int(xy[1])) | |
def distance(pt0, pt1): | |
return abs(pt0[0] - pt1[0]) + abs(pt0[1] - pt1[1]) | |
# closest idx. -1 if multiple closest. | |
def closest(max_xy, xy, index_points): | |
closest_pt = max_xy[0] + max_xy[1] | |
closest_idx = -1 | |
# This loop runs once in python3 | |
for idx, pt in index_points: | |
d = distance(pt, xy) | |
if d < closest_pt: | |
closest_pt = d | |
closest_idx = idx | |
elif d == closest_pt: | |
closest_idx = -1 | |
return closest_idx | |
def map_points(pt_dict, max_xy, points): | |
index_points = zip(range(0, len(points)), points) | |
for x in range(0, max_xy[0]+1): | |
for y in range(0, max_xy[1]+1): | |
pt_dict[(x,y)] = closest(max_xy, (x,y), index_points) | |
# Walk the border, collecting indexes. These are infinite. | |
def filter_infinite(max_xy, pt_dict): | |
filter_set = set() | |
for x in range(0, max_xy[0]+1): | |
filter_set.add(pt_dict[(x,0)]) | |
for x in range(0, max_xy[0]+1): | |
filter_set.add(pt_dict[(x,max_xy[1])]) | |
for y in range(0, max_xy[1]+1): | |
filter_set.add(pt_dict[(0,y)]) | |
for x in range(0, max_xy[1]+1): | |
filter_set.add(pt_dict[(max_xy[0],y)]) | |
for pt, idx in pt_dict.items(): | |
if idx in filter_set: | |
pt_dict[pt] = -1 | |
def max_area(pt_dict): | |
# From idxs to the number of times they appear | |
cnt_dict = {} | |
for pt, idx in pt_dict.items(): | |
if idx not in cnt_dict: | |
cnt_dict[idx] = 1 | |
else: | |
cnt_dict[idx] += 1 | |
max_cnt = 0 | |
for idx, cnt in cnt_dict.items(): | |
if cnt > max_cnt and idx != -1: | |
max_cnt = cnt | |
return max_cnt | |
def main(): | |
points = [] | |
with open(filepath) as fp: | |
lines = fp.readlines() | |
points = [x for x in lines if x != '\n'] | |
mk_pairs(points) | |
max_xy = max_bounds(points) | |
# Map from points in the grid to their closest designated point. | |
pt_dict = {} | |
map_points(pt_dict, max_xy, points) | |
filter_infinite(max_xy, pt_dict) | |
res = max_area(pt_dict) | |
print(res) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment