36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
const input = ""
|
|
|
|
console.log(part1(input))
|
|
console.log(part2(input))
|
|
|
|
type Item = [number, number]
|
|
const [start, end] = [0, 1]
|
|
|
|
function part1(input: string): number {
|
|
const [db, ids] = parseInput(input)
|
|
return ids.filter(currentId => {
|
|
return db.find(id => id[start] <= currentId && id[end] >= currentId)
|
|
}).length
|
|
}
|
|
|
|
function part2(input: string): number {
|
|
const [db, _] = parseInput(input)
|
|
return db.reduce((sum, i) => sum + (i[end] - i[start] + 1), 0)
|
|
}
|
|
|
|
function parseInput(input: string): [Item[], number[]] {
|
|
const [dbLines, itemsLines] = input.trim().split('\n\n')
|
|
.map(n => n.trim().split('\n'))
|
|
|
|
const db = dbLines.map(line => line.split('-').map(n => parseInt(n, 10)) as Item)
|
|
.reduce((db: Item[], newItem: Item) => {
|
|
const mergedInterval = db
|
|
.filter(item => newItem[start] <= item[end] && newItem[end] >= item[start])
|
|
.reduce((acc, item) => [Math.min(acc[start], item[start]), Math.max(acc[end], item[end])], newItem)
|
|
const remaining = db.filter(item => (item[end] < newItem[start] || item[start] > newItem[end]))
|
|
return [...remaining, mergedInterval] as Item[]
|
|
}, [] as Item[])
|
|
|
|
return [db, itemsLines.map(Number)]
|
|
}
|