-
-
Save ChiriVulpes/bf64841084d95b4e5964c6b974e91fbe to your computer and use it in GitHub Desktop.
advent of code 2024 chiri solutions day 5
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
const [rulesInput, updatesInput] = input.split("\n\n") | |
const rules = Object.fromEntries(Object.entries(Object.groupBy(rulesInput.split("\n").map(rule => rule.split("|").map(n => +n)), a => a[1])).map(([page, dependencies]) => [page, dependencies.map(dependency => dependency[0])])) | |
const dependants = Object.fromEntries(Object.entries(Object.groupBy(rulesInput.split("\n").map(rule => rule.split("|").map(n => +n)), a => a[0])).map(([page, dependants]) => [page, dependants.map(dependant => dependant[1])])) | |
const updates = updatesInput.split("\n").map(update => update.split(",").map(n => +n)) | |
const { validUpdates, invalidUpdates } = Object.groupBy(updates, update => ruleCheck(update) ? "validUpdates" : "invalidUpdates") | |
const fixedUpdates = invalidUpdates.map(update => ruleSort(update)) | |
;[sumMiddlePages(validUpdates), sumMiddlePages(fixedUpdates)] | |
function sumMiddlePages (updates) { | |
return updates.map(update => update[Math.floor(update.length / 2)]).reduce((c, v) => c + v, 0) | |
} | |
function ruleCheck (update) { | |
for (let i = update.length - 1; i > 0; i--) | |
for (let c = 0; c < i; c++) | |
if (dependants[update[i]].includes(update[c])) | |
return false | |
return true | |
} | |
function ruleSort (update) { | |
const loaded = [] | |
for (const page of update) | |
loadPage(page) | |
return loaded | |
function loadPage (page) { | |
if (loaded.includes(page)) | |
return | |
const dependencies = rules[page] | |
for (const dependency of dependencies) | |
if (update.includes(dependency)) | |
loadPage(dependency) | |
loaded.push(page) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment