-
-
Save ChiriVulpes/4d74719ae90f77eb37fa40b19deca630 to your computer and use it in GitHub Desktop.
advent of code 2024 chiri solutions day 2
This file contains hidden or 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
input.split(/\s*\n\s*/g) | |
.map((report, i, a, | |
levels = report.split(/\s+/g).map(level => +level), | |
dirs = new Set(levels.map((v, i) => i === 0 ? 10 : Math.sign(v - levels[i - 1]))), | |
dists = levels.map((v, i) => i === 0 ? 1 : Math.abs(v - (levels[i - 1] ?? 0))), | |
) => ({ | |
levels, | |
dirs, | |
dists, | |
safe: dirs.size === 2 && dists.every(dist => dist >= 1 && dist <= 3), | |
})).filter(report => report.safe) |
This file contains hidden or 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
function count(arr, filter) { return arr.reduce((c, v) => c + +!!filter(v), 0) } | |
input.split(/\s*\n\s*/g) | |
.filter(report => isReportSafe(report.split(/\s+/g).map(level => +level))) | |
function isReportSafe(levels, recursive = false) { | |
const dirs = levels.map((v, i) => i === 0 ? 0 : Math.sign(v - levels[i - 1])) | |
dirs.shift() | |
const dists = levels.map((v, i) => i === 0 ? 0 : Math.abs(v - (levels[i - 1] ?? 0))) | |
dists.shift() | |
const invalidDistsCount = count(dists, dist => dist < 1 || dist > 3) | |
if (invalidDistsCount > 2) | |
return false | |
if (!invalidDistsCount && dirs[0] !== 0 && new Set(dirs).size === 1) | |
return true | |
if (recursive) | |
return false // if the above checks failed this tweak to the report is unsafe | |
const noDirs = count(dirs, dir => dir === 0) | |
if (noDirs > 1) | |
return false // 0 more than once is always invalid | |
const negDirs = count(dirs, dir => dir === -1) | |
const posDirs = count(dirs, dir => dir === 1) | |
if (negDirs > 1 && posDirs > 1) | |
return false // both directions each more than once is always invalid | |
return levels.some((v, i) => isReportSafe(levels.toSpliced(i, 1), true)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment