aoc24/solutions/02.ts
2024-12-04 23:19:34 +01:00

43 lines
No EOL
1.6 KiB
TypeScript

import { solvables } from "../main.ts";
import type { Solvable } from "../solvable.ts";
import { readInput } from "../utils.ts";
class DayTwo implements Solvable {
input = readInput('02')
public part1(): DayTwo {
const reports = this.input.trim().split("\n").map(line => line.split(' ').map(level => Number.parseInt(level)))
const slidingWindow = (levels: number[]): boolean => {
const gradients: ("ascending" | "descending")[] = []
let [i,j] = [0,1]
while (j < levels.length) {
// is unsafe if ascent / descend bigger than 3 or smaller than 1
const diff = Math.abs(levels[i] - levels[j])
if (diff > 3 || diff < 1) {
return false
}
// calculate positive or negative gradient
if (levels[i] < levels[j]) {
gradients.push("ascending")
} else if (levels[i] > levels[j]) {
gradients.push("descending")
}
i++
j++
}
// is safe and constant gradient?
const constantGradient = gradients.every((gradient) => gradient === "ascending") || gradients.every((gradient) => gradient === "descending")
return constantGradient
}
const result = reports.map(levels => slidingWindow(levels)).filter(level_safe => level_safe === true).length
console.log(result)
return this
}
public part2(): DayTwo {
return this
}
}
solvables.push(new DayTwo())