-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_5.js
90 lines (73 loc) · 2.65 KB
/
day_5.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
const fs = require('fs')
const getCoversPoints = (points) => {
const coverpoints = []
let currX = points.x1
let currY = points.y1
const xShouldBeAsc = points.x1 < points.x2
const yShouldBeAsc = points.y1 < points.y2
do {
coverpoints.push({x: currX, y: currY})
if (currX !== points.x2) {
xShouldBeAsc ? currX++ : currX--
}
if (currY !== points.y2) {
yShouldBeAsc ? currY++ : currY--
}
} while (!coverpoints.find( (value) => value.x === points.x2 && value.y === points.y2))
return coverpoints
}
const formatLine = (line) => {
const values = line.split(' -> ').map(segment => segment.split(',')).flat()
return {
x1: parseInt(values[0], 10),
y1: parseInt(values[1], 10),
x2: parseInt(values[2], 10),
y2: parseInt(values[3], 10),
}
}
const toKey = (point) => `${point.x}_${point.y}`
const getDuplicates = (arr) => {
const flattenArray = {}
arr.forEach((values) => {
values.forEach((value) => {
if (flattenArray[toKey(value)]) {
flattenArray[toKey(value)]++
} else {
flattenArray[toKey(value)] = 1
}
})
})
return flattenArray
}
const filterHorizontalAndVerticalLines = (line) => line.x1 === line.x2 || line.y1 === line.y2
// PART ONE
fs.readFile('./inputs/5.txt', 'utf8', (err, response) => {
if (err) throw err
const data = response.split('\n')
const formattedLines = data.map(line => formatLine(line))
const onlyHorizontalAndVerticalLines = formattedLines.filter(filterHorizontalAndVerticalLines)
const coversPoints = onlyHorizontalAndVerticalLines.map(line => getCoversPoints(line))
const pointsWithDuplicateScore = getDuplicates(coversPoints)
const onlyDuplicates = []
for (const keyDup of Object.keys(pointsWithDuplicateScore)) {
if (pointsWithDuplicateScore[keyDup] > 1) {
onlyDuplicates.push(pointsWithDuplicateScore[keyDup])
}
}
console.log(onlyDuplicates.length)
})
// PART TWO
fs.readFile('./inputs/5.txt', 'utf8', (err, response) => {
if (err) throw err
const data = response.split('\n')
const formattedLines = data.map(line => formatLine(line))
const coversPoints = formattedLines.map(line => getCoversPoints(line))
const pointsWithDuplicateScore = getDuplicates(coversPoints)
const onlyDuplicates = []
for (const keyDup of Object.keys(pointsWithDuplicateScore)) {
if (pointsWithDuplicateScore[keyDup] > 1) {
onlyDuplicates.push(pointsWithDuplicateScore[keyDup])
}
}
console.log(onlyDuplicates.length)
})