-
Notifications
You must be signed in to change notification settings - Fork 5
/
day04.mjs
46 lines (38 loc) · 1.25 KB
/
day04.mjs
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
import { readFileSync } from "node:fs";
const lines = readFileSync("day04.txt", { encoding: "utf-8" }) // read day??.txt content
.replace(/\r/g, "") // remove all \r characters to avoid issues on Windows
.trim() // Remove starting/ending whitespace
.split("\n"); // Split on newline
function part1() {
const res = lines.map((line) => {
const [interval1, interval2] = line
.split(",")
.map((interval) => interval.split("-").map(Number))
.sort((a, b) => {
const oneSize = a[1] - a[0];
const twoSize = b[1] - b[0];
return twoSize - oneSize;
});
const oneFullContainsTwo =
interval1[0] <= interval2[0] && interval1[1] >= interval2[1];
return oneFullContainsTwo ? 1 : 0;
});
console.log(res.reduce((a, b) => a + b, 0));
}
function part2() {
const res = lines.map((line) => {
const [first, second] = line
.split(",")
.map((interval) => interval.split("-").map(Number))
.sort((a, b) => {
const oneSize = a[1] - a[0];
const twoSize = b[1] - b[0];
return twoSize - oneSize;
});
const overlap = first[1] >= second[0] && second[1] >= first[0];
return overlap ? 1 : 0;
});
console.log(res.reduce((a, b) => a + b, 0));
}
part1();
part2();