Skip to content

Instantly share code, notes, and snippets.

@waspeer
Created December 4, 2024 13:13
Show Gist options
  • Save waspeer/905eed476d9e0dc1bd8a6993af798f66 to your computer and use it in GitHub Desktop.
Save waspeer/905eed476d9e0dc1bd8a6993af798f66 to your computer and use it in GitHub Desktop.
const data = await Deno.readTextFile("./day2.txt");
const reports = data.split("\n").map((line) => line.split(/\s+/).map(Number));
function checkIsSafe(report: number[], index = 0, dampened = false): boolean {
const a = report[index];
const b = report[index + 1];
const diff = b - a;
const direction = report[1] - report[0] < 0 ? "dec" : "inc";
const isLast = index + 1 === report.length;
if (
diff === 0 ||
Math.abs(diff) > 3 ||
(direction === "inc" && diff < 0) ||
(direction === "dec" && diff > 0)
) {
if (dampened) {
return false;
}
if (isLast) {
return true;
}
const dropBefore = checkIsSafe(
report.toSpliced(Math.max(index - 1, 0), 1),
Math.max(0, index - 2),
true
);
if (dropBefore) {
return true;
}
const dropCurrent =
index === 0
? dropBefore
: checkIsSafe(report.toSpliced(index, 1), Math.min(0, index - 1), true);
if (dropCurrent) {
return true;
}
const dropNext = checkIsSafe(report.toSpliced(index + 1, 1), index, true);
if (dropNext) {
return true;
}
return false;
}
if (isLast) {
return true;
}
return checkIsSafe(report, index + 1, dampened);
}
let safe = 0;
for (const report of reports) {
if (checkIsSafe(report)) {
safe++;
}
}
console.log("safe", safe);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment