day 2 (refactor)

This commit is contained in:
2024-12-03 12:37:07 +01:00
parent e448cf2671
commit 8bf91cfc9a

View File

@@ -1,3 +1,5 @@
import * as R from "remeda";
export async function day2(input: string) { export async function day2(input: string) {
const lines = input.split("\n"); const lines = input.split("\n");
let count = 0; let count = 0;
@@ -44,33 +46,10 @@ export async function day2part2(input: string) {
} }
function isSafe(levels: number[]) { function isSafe(levels: number[]) {
let increasing = null; const diffs = R.zip(levels, levels.slice(1)).map(([a, b]) => a - b);
let safe = true;
for (let i = 0; i < levels.length - 1; i++) { return (
const current = levels[i]; diffs.every((d) => 1 <= d && d <= 3) ||
const next = levels[i + 1]; diffs.every((d) => -1 >= d && d >= -3)
const diff = Math.abs(next - current); );
if (diff > 3 || diff < 1) {
safe = false;
break;
}
if (i === 0) {
increasing = next > current;
continue;
}
if (increasing && next <= current) {
safe = false;
break;
}
if (!increasing && next >= current) {
safe = false;
break;
}
}
return safe;
} }