-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday5.js
93 lines (81 loc) · 2.29 KB
/
day5.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
const fs = require('fs');
const assert = require('assert');
const rawData = fs.readFileSync('./data/day5.txt', 'utf8').split('\n');
const data = rawData.reduce((acc, row) => {
const entries = row.split(' -> ');
acc.push(
entries.reduce((acc2, item) => {
nextItem = item.split(',').map((item) => parseInt(item));
acc2.push({ x: nextItem[0], y: nextItem[1] });
return acc2;
}, [])
);
return acc;
}, []);
const gridWidth = Math.max.apply(
Math,
data.map((item) => {
value = Math.max(item[0].x, item[1].x);
return value + 1;
})
);
const gridHeight = Math.max.apply(
Math,
data.map((item) => {
value = Math.max(item[0].y, item[1].y);
return value + 1;
})
);
function fillGridPoints(isPart1) {
const defaultRow = new Array(gridWidth).fill(0);
const emptyGrid = new Array(gridHeight).fill(null);
const grid = emptyGrid.map(() => {
return JSON.parse(JSON.stringify(defaultRow));
});
// const grid = new Array(gridHeight).fill(new Array(rowLength));
data.forEach((coordinates) => {
const isDiagonal =
coordinates[0].y !== coordinates[1].y &&
coordinates[0].x !== coordinates[1].x;
if (isPart1 && isDiagonal) {
return;
}
const startingColumn = coordinates[0].x;
const endingColumn = coordinates[1].x;
const startingRow = coordinates[0].y;
const endingRow = coordinates[1].y;
const isLtR = startingColumn <= endingColumn;
const isTtB = startingRow <= endingRow;
for (
let r = startingRow;
isTtB ? r <= endingRow : r >= endingRow;
isTtB ? r++ : r--
) {
for (
let c = startingColumn;
isLtR ? c <= endingColumn : c >= endingColumn;
isLtR ? c++ : c--
) {
grid[r][c] = grid[r][c] + 1;
if (isDiagonal) {
isTtB ? r++ : r--;
}
}
}
});
return grid;
}
function calculateOverLappingPoints(grid) {
return grid.reduce((acc, row) => {
acc += row.reduce((acc2, point) => {
return point > 1 ? (acc2 = acc2 + 1) : acc2;
}, 0);
return acc;
}, 0);
}
const part1Grid = fillGridPoints(true);
const part1Answer = calculateOverLappingPoints(part1Grid);
const part2Grid = fillGridPoints();
const part2Answer = calculateOverLappingPoints(part2Grid);
console.log(part1Answer);
console.log(part2Answer);