Skip to content

Commit c60f6ea

Browse files
feat(2019-day-03): trace wires to find their length at intersections
1 parent 173ab6d commit c60f6ea

File tree

2 files changed

+51
-3
lines changed

2 files changed

+51
-3
lines changed

2019/day-03/wires.js

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,49 @@ const isCloser = {
4646
}
4747
}
4848
}
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
4964
}
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
5092
}
5193

5294
const getClosesetIntersection = ({
@@ -66,8 +108,14 @@ const getClosesetIntersection = ({
66108
return intersections[0]
67109
}
68110

111+
const getClosesetIntersectionByWire = (intersections) => {
112+
intersections.sort(isCloserByWire)
113+
}
114+
69115
module.exports = {
70116
elfWireToSVGPath,
71117
findWireIntersections,
72-
getClosesetIntersection
118+
getClosesetIntersection,
119+
getIntersectionWireDistance,
120+
getClosestIntersectionByWireDistance
73121
}

2019/day-03/wires.test.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* eslint-env mocha */
22
const expect = require('chai').expect
3-
const { elfWireToSVGPath, findWireIntersections, getClosesetIntersection } = require('./wires')
3+
const { elfWireToSVGPath, findWireIntersections, getClosesetIntersection, getIntersectionWireDistance, getClosesetIntersectionByWire } = require('./wires')
44

55
describe('--- 2019 Day 3: Crossed Wires ---', () => {
66
describe('Part 1', () => {
@@ -69,7 +69,7 @@ describe('--- 2019 Day 3: Crossed Wires ---', () => {
6969
expect(actual).to.deep.equal(expected)
7070
})
7171
})
72-
describe('getClosestIntersectionByWire()', () => {
72+
describe('getClosestIntersectionByWireDistance()', () => {
7373
it('can be used to find the wire distance to the closest intersection', () => {
7474
const wiresets = [
7575
[

0 commit comments

Comments
 (0)