Day 4
This commit is contained in:
parent
9c6fcba3d1
commit
7980e848e1
55
4/solution.mjs
Normal file
55
4/solution.mjs
Normal file
@ -0,0 +1,55 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const input = readFileSync('input', 'utf-8');
|
||||
|
||||
class Range {
|
||||
constructor(start, end) {
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
|
||||
if (this.start > this.end) {
|
||||
throw new Error('Invalid range');
|
||||
}
|
||||
}
|
||||
|
||||
containsRange(range) {
|
||||
return (
|
||||
this.start <= range.start &&
|
||||
this.end >= range.end
|
||||
);
|
||||
}
|
||||
|
||||
overlaps(range) {
|
||||
return (
|
||||
(range.start >= this.start && range.start <= this.end) ||
|
||||
(this.start >= range.start && this.start <= range.end)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const pairs = input
|
||||
.split('\n')
|
||||
.filter(line => line)
|
||||
.map(line => line
|
||||
.split(',')
|
||||
.map(range => new Range(...range
|
||||
.split('-')
|
||||
.map(num => parseInt(num))
|
||||
))
|
||||
);
|
||||
|
||||
const containedPairCount = pairs
|
||||
.map(pair =>
|
||||
pair[0].containsRange(pair[1]) ||
|
||||
pair[1].containsRange(pair[0])
|
||||
)
|
||||
.reduce((total, contains) => total + Number(contains), 0);
|
||||
|
||||
console.log(`Contained pair count: ${containedPairCount}`);
|
||||
|
||||
const overlappingPairCount = pairs
|
||||
.map(pair => pair[0].overlaps(pair[1]))
|
||||
.reduce((total, overlaps) => total + Number(overlaps), 0)
|
||||
|
||||
console.log(`Overlapping pair count: ${overlappingPairCount}`);
|
||||
|
Loading…
Reference in New Issue
Block a user