From ccf3e827a98e8d1ea5c52ed470ed94e9ca3e7153 Mon Sep 17 00:00:00 2001 From: mtrx Date: Wed, 4 Dec 2024 23:15:42 +0100 Subject: [PATCH] day 2 part 1 --- solutions/01.ts | 9 ++++++--- solutions/02.ts | 29 ++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/solutions/01.ts b/solutions/01.ts index 9fd198d..29aa8c5 100644 --- a/solutions/01.ts +++ b/solutions/01.ts @@ -7,9 +7,12 @@ 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 vals = this.input + .trim() + .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 --git a/solutions/02.ts b/solutions/02.ts index 49672b6..bdeaa01 100644 --- a/solutions/02.ts +++ b/solutions/02.ts @@ -7,7 +7,34 @@ class DayTwo implements Solvable { input = readInput('02') public part1(): DayTwo { - console.log("test") + 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") + } else { + return false + } + 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 {