|
| 1 | +const intersection = require('path-intersection') |
| 2 | +const { distance } = require('../../2018/day-06/coordinates') // Manhattan distance function from last year |
| 3 | + |
| 4 | +const elfWireToSVGPath = (path) => { |
| 5 | + const replacements = { |
| 6 | + R: 'h', // R(ight) becomes relative positive horizontal lineto |
| 7 | + L: 'h-', // L(eft) becomes relative negative horizontal lineto |
| 8 | + U: 'v-', // U(p) becomes relative negative vertical line |
| 9 | + D: 'v', // D(own) becomes relative positive vertical line |
| 10 | + ',': ' ' // Separators are done with whitespace |
| 11 | + } |
| 12 | + path = path.trim() |
| 13 | + |
| 14 | + const pattern = new RegExp(Object.keys(replacements).join('|'), 'gi') |
| 15 | + path = path.replace(pattern, (match) => { |
| 16 | + return replacements[match] |
| 17 | + }) |
| 18 | + |
| 19 | + return `M0,0 ${path}` |
| 20 | +} |
| 21 | + |
| 22 | +const findWireIntersections = (wires) => { |
| 23 | + wires = wires.map(elfWireToSVGPath) |
| 24 | + const ints = intersection( |
| 25 | + ...wires |
| 26 | + ).map((point) => { |
| 27 | + return { x: parseInt(point.x), y: parseInt(point.y) } |
| 28 | + }) |
| 29 | + |
| 30 | + return ints.sort(isCloser) |
| 31 | +} |
| 32 | + |
| 33 | +const isCloser = (intA, intB) => { |
| 34 | + const origin = { x: 0, y: 0 } |
| 35 | + intA.distance = distance(origin, intA) |
| 36 | + intB.distance = distance(origin, intB) |
| 37 | + if (intA.distance < intB.distance) { |
| 38 | + return -1 |
| 39 | + } |
| 40 | + if (intA.distance > intB.distance) { |
| 41 | + return 1 |
| 42 | + } |
| 43 | + if (intA.distance === intB.distance) { |
| 44 | + return 0 |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +const getClosesetIntersection = (intersections) => { |
| 49 | + intersections.sort(isCloser) |
| 50 | + // Skip the origin since all wires start at origin |
| 51 | + return intersections[1] |
| 52 | +} |
| 53 | + |
| 54 | +module.exports = { |
| 55 | + elfWireToSVGPath, |
| 56 | + findWireIntersections, |
| 57 | + getClosesetIntersection |
| 58 | +} |
0 commit comments