Created
December 2, 2024 09:27
-
-
Save kirkegaard/2943e5cc1c622d4d516f2aa625488b8a to your computer and use it in GitHub Desktop.
advent of code day 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const input = await Deno.readTextFile("input.txt"); | |
const data = input.split("\n"); | |
const isSafe = (levels: number[]): boolean => { | |
const diffs = levels.slice(1).map((num, idx) => num - levels[idx]); | |
// Stupid off by one error >:( | |
if (diffs.length === 0) { | |
return false; | |
} | |
const increasing = diffs.every((diff) => diff >= 1 && diff <= 3); | |
const decreasing = diffs.every((diff) => diff <= -1 && diff >= -3); | |
return increasing || decreasing; | |
}; | |
const canBeSafeWithOneRemoval = (levels: number[]): boolean => { | |
for (let i = 0; i < levels.length; i++) { | |
const modifiedLevels = levels.slice(0, i).concat(levels.slice(i + 1)); | |
if (isSafe(modifiedLevels)) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
let safeCount = 0; | |
let safeIfOneRemovedCount = 0; | |
data.forEach((row) => { | |
const levels = row.split(" ").map((num) => Number(num.trim())); | |
if (isSafe(levels)) { | |
safeCount++; | |
} | |
if (isSafe(levels) || canBeSafeWithOneRemoval(levels)) { | |
safeIfOneRemovedCount++; | |
} | |
}); | |
console.log({ safeCount, safeIfOneRemovedCount }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment