@@ -46,7 +46,49 @@ const isCloser = {
46
46
}
47
47
}
48
48
}
49
+
50
+ const advance = ( { segment, remaining, distance, current } ) => {
51
+ // Track the step
52
+ switch ( direction ) {
53
+ case 'U' : // Up
54
+ current . y += - dimension
55
+ break
56
+ case 'D' : // Down
57
+ current . y += dimension
58
+ break
59
+ case 'R' : // Right
60
+ current . x += dimension
61
+ break
62
+ case 'L' : // Left
63
+ current . x += - dimension
49
64
}
65
+ remaining += - 1
66
+ distance ++
67
+ }
68
+
69
+ const getIntersectionWireDistance = ( { intersection, wires } ) => {
70
+ intersection . wireDistance = 0
71
+
72
+ wires . reduce ( ( wire ) => {
73
+ const segments = wire . split ( ',' )
74
+ const current = { x : 0 , y : 0 }
75
+ const distance = 0
76
+
77
+ segments . forEach ( ( segment , idx ) => {
78
+ const direction = segment . slice ( 0 , 1 )
79
+ const length = parseInt ( segment . slice ( 1 ) )
80
+ for ( let d = 0 ; d < length ; d ++ ) {
81
+ advance ( { direction, remaining, distance, current } )
82
+ // Reached the desired intersection, stop counting and track result
83
+ if ( current . x === intersection . x && current . y === intersection . y ) {
84
+ intersection . wireDistance += distance
85
+ break
86
+ }
87
+ }
88
+ } )
89
+ } , 0 )
90
+
91
+ return intersection . wireDistance
50
92
}
51
93
52
94
const getClosesetIntersection = ( {
@@ -66,8 +108,14 @@ const getClosesetIntersection = ({
66
108
return intersections [ 0 ]
67
109
}
68
110
111
+ const getClosesetIntersectionByWire = ( intersections ) => {
112
+ intersections . sort ( isCloserByWire )
113
+ }
114
+
69
115
module . exports = {
70
116
elfWireToSVGPath,
71
117
findWireIntersections,
72
- getClosesetIntersection
118
+ getClosesetIntersection,
119
+ getIntersectionWireDistance,
120
+ getClosestIntersectionByWireDistance
73
121
}
0 commit comments