-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-2.py
105 lines (82 loc) · 2.58 KB
/
3-2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# use dictionary to map coordinates
import csv
segments = [] # empty list for dictionaries (1 for each path)
coords = [0,0] # x/y coordinates
# @param c string - cartesian string to parse. format: "x,y"
def calc_steps(coord):
# print("coord: ", coord);
steps1 = segments[0].index(coord) + 1
steps2 = segments[1].index(coord) + 1
# print("steps1: ", steps1)
# print("steps2: ", steps2)
# print("sum: ", steps1 + steps2)
return steps1 + steps2
# @param c string - cartesian string to parse. format: "x,y"
def parse_coord(c):
return list(map(int, c.split(',')))
# returns intersection of 2 lists
def intersection(l1, l2):
return list(set(l1).intersection(l2))
"""
@param dir string - direction line is going (possible values: 'U', 'D', 'L', 'R')
@param len int - the length of the line (equal to the number of segments it produces)
@param segs Map - the map for which to store the segments
"""
def populate_segments(dir, len, segs):
c = coords.copy()
for i in range(0, len):
# print("-"*10)
# print("dir: ", dir)
# print("len: ", len)
# f = ','.join(map(str, c)) # from
c = increment_coords(dir, c)
t = ','.join(map(str, c)) # to
# print("from: ", f)
# print("to: ", t)
segs.append(t)
# print("coords: ", coords)
def increment_coords(dir, coords=coords, len=1):
if dir == 'U':
coords[1] += len
elif dir == 'D':
coords[1] -= len
elif dir == 'R':
coords[0] += len
elif dir == 'L':
coords[0] -= len
else:
print("invalid direction code")
exit()
return coords
# read file
with open("3.txt", "r") as f:
reader = csv.reader(f)
points = list(reader)
print("points: ", points)
# parse into map
for i, point_list in enumerate(points):
coords = [0,0]
segments.append([])
for point in point_list:
# find direction
# track direction on grid
# log in segments
direction = point[0]
length = int(point[1:])
# print("dir: ", direction)
# print("length: ", length)
populate_segments(direction, length, segments[i])
increment_coords(direction, coords, length)
print("segments: ")
print(segments[0])
print(segments[1])
# find intersections
intersections = intersection(segments[0], segments[1])
print("intersections: ", intersections)
# find shortest step distance
shortest = calc_steps(intersections[0])
for point in intersections:
s = calc_steps(point)
if s < shortest:
shortest = s
print("Shortest Step Distance: ", shortest)