-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp3.js
98 lines (79 loc) · 2.23 KB
/
p3.js
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
const fs = require('fs')
fs.readFile('./p3_data.txt', 'utf8', function(err, data) {
let rows = data.split('\n')
let wire1 = rows[0].split(',')
let wire2 = rows[1].split(',')
let wire1Coords = mapCoords(wire1)
let wire2Coords = mapCoords(wire2)
let matches = new Set()
matches = [... wire1Coords.points.keys()].filter(point => wire2Coords.points.get(point))
let closest = matches.reduce((acc, point) => {
let sum = wire1Coords.points.get(point) + wire2Coords.points.get(point)
return Math.min(acc, sum)
}, Number.MAX_SAFE_INTEGER)
console.log(closest)
})
function mapCoords(wire) {
let allCoords = []
let allPoints = new Map()
let d = 0
wire.forEach((item, index) => {
if(index === 0) {
let {coord, points, distance} = getCoords(item)
d = distance
allCoords[index] = coord
allPoints = points
return
}
let { coord, points, distance } = getCoords(item, allCoords[index-1], allPoints, d)
d = distance
allCoords[index] = coord
allPoints = points
})
return { coords: allCoords, points: allPoints }
}
function getCoords(move, coord = [0, 0], points = new Map(), d = 1) {
let direction = move[0]
let num = Number(move.slice(1))
let start
switch(direction) {
case 'L':
start = coord[0]
while(start !== coord[0] - num) {
start--
d++
points.set([start - 1, coord[1]].join(','), d)
}
coord = [coord[0] - num, coord[1]]
break;
case 'R':
start = coord[0]
while(start !== coord[0] + num) {
start++
d++
points.set([start + 1, coord[1]].join(','), d)
}
coord = [coord[0] + num, coord[1]]
break;
case 'U':
start = coord[1]
while(start !== coord[1] + num) {
start++
d++
points.set([coord[0], start + 1].join(','), d)
}
coord = [coord[0], coord[1] + num]
break;
case 'D':
start = coord[1]
while(start !== coord[1] - num) {
start--
d++
points.set([coord[0], start - 1].join(','), d)
}
coord = [coord[0], coord[1] - num]
break;
default:
}
return { coord, points, distance: d }
}