-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path05.js
148 lines (141 loc) · 2.59 KB
/
05.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
'use strict';
/**
* @param {string} d
*/
export const part1 = async d => {
let maxX = 0;
let maxY = 0;
const grid = [];
const data = d.split('\n').map(e => e.split(' -> ').map(e => {
const pos = e.split(',').map(e => parseInt(e, 10));
maxX = Math.max(maxX, pos[0]);
maxY = Math.max(maxY, pos[1]);
return pos;
}));
maxX++;
maxY++;
for (let x = 0; x < maxX; x++) {
grid.push([]);
for (let y = 0; y < maxY; y++) {
grid[x].push(0);
}
}
data.forEach(line => {
const x1 = line[0][0];
const y1 = line[0][1];
const x2 = line[1][0];
const y2 = line[1][1];
if (x1 == x2 && y1 != y2) {
// hor line
const x = x1;
if (y1 > y2) {
for (let y = y2; y <= y1; y++) {
grid[x][y]++;
}
}
else {
for (let y = y1; y <= y2; y++) {
grid[x][y]++;
}
}
}
else if (y1 == y2 && x1 != x2) {
// ver line
const y = y1;
if (x1 > x2) {
for (let x = x2; x <= x1; x++) {
grid[x][y]++;
}
}
else {
for (let x = x1; x <= x2; x++) {
grid[x][y]++;
}
}
}
else {
// Ignore this line for part 1
}
});
return grid.reduce((p, v) => p + v.reduce((p, v) => {
if (v > 1) {
return p + 1;
}
return p;
}, 0), 0);
};
/**
* @param {string} d
*/
export const part2 = async d => {
let maxX = 0;
let maxY = 0;
const grid = [];
const data = d.split('\n').map(e => e.split(' -> ').map(e => {
const pos = e.split(',').map(e => parseInt(e, 10));
maxX = Math.max(maxX, pos[0]);
maxY = Math.max(maxY, pos[1]);
return pos;
}));
maxX++;
maxY++;
for (let x = 0; x < maxX; x++) {
grid.push([]);
for (let y = 0; y < maxY; y++) {
grid[x].push(0);
}
}
data.forEach(line => {
const x1 = line[0][0];
const y1 = line[0][1];
const x2 = line[1][0];
const y2 = line[1][1];
if (x1 == x2 && y1 != y2) {
// hor line
const x = x1;
if (y1 > y2) {
for (let y = y2; y <= y1; y++) {
grid[x][y]++;
}
}
else {
for (let y = y1; y <= y2; y++) {
grid[x][y]++;
}
}
}
else if (y1 == y2 && x1 != x2) {
// ver line
const y = y1;
if (x1 > x2) {
for (let x = x2; x <= x1; x++) {
grid[x][y]++;
}
}
else {
for (let x = x1; x <= x2; x++) {
grid[x][y]++;
}
}
}
else {
// 45d line
const dx = (x1 == x2) ? 0 : ((x1 > x2) ? -1 : 1);
const dy = (y1 == y2) ? 0 : ((y1 > y2) ? -1 : 1);
let x = x1;
let y = y1;
while (x != (x2 + dx) && y != (y2 + dy)) {
grid[x][y]++;
x += dx;
y += dy;
}
}
});
return grid.reduce((p, v) => p + v.reduce((p, v) => {
if (v > 1) {
return p + 1;
}
return p;
}, 0), 0);
// 18418 too low
};