aoc24/solutions/01.ts
2024-12-08 00:46:45 +01:00

42 lines
No EOL
1.5 KiB
TypeScript

import { solvables } from "../main.ts";
import type { Solvable } from "../solvable.ts";
import { readInput } from "../utils.ts";
class DayOne implements Solvable {
input = readInput('01')
public part1(): Promise<DayOne> {
const vals = this.input
.split("\n")
.map(line => line.split(' ').map(col => Number.parseInt(col)))
const left = vals.map(line => line[0]).sort()
const right = vals.map(line => line[1]).sort()
const diff: number[] = []
left.forEach((left, idx) => {
diff.push(Math.abs(left - right[idx]))
})
const result = diff.reduce((prev, curr) => prev + curr)
console.log(result)
return new Promise(() => this)
}
public part2(): Promise<DayOne> {
const vals = this.input.trim().split("\n").map(line => line.split(' '))
const left = vals.map(line => Number.parseInt(line[0])).sort()
const right = vals.map(line => Number.parseInt(line[1])).sort()
const countedOccurences: Map<number, number> = new Map()
left.forEach(left_val => countedOccurences.set(left_val, right.filter(right_val => left_val === right_val).length))
const result = countedOccurences
.entries()
.map(([left_val, occurences]) => left_val * occurences)
.reduce((prev, curr) => prev + curr)
console.log(result)
return new Promise(() => this)
}
}
solvables.push(new DayOne())