40 lines
1.4 KiB
TypeScript
40 lines
1.4 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(): 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 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 this
|
||
|
}
|
||
|
|
||
|
public part2(): 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 this
|
||
|
}
|
||
|
}
|
||
|
|
||
|
solvables.push(new DayOne())
|