Created
December 16, 2020 13:36
-
-
Save isaacplmann/5d28ee7e7dbb407bbba101d5e88058c2 to your computer and use it in GitHub Desktop.
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 [rulesRaw, yourTicketRaw, nearbyTicketsRaw] = input2.split('\n\n'); | |
const yourTicket = yourTicketRaw | |
.split('\n')[1] | |
.split(',') | |
.map((n) => Number(n)); | |
const locations = new Array(yourTicket.length).fill(0).map((_, i) => i); | |
const rules = rulesRaw.split('\n').map((line) => { | |
const [name, ruleStr] = line.split(': '); | |
return { | |
name, | |
locations, | |
ranges: ruleStr | |
.split(' or ') | |
.map((range) => range.split('-').map((n) => Number(n))), | |
}; | |
}); | |
const nearbyTickets = nearbyTicketsRaw | |
.split('\n') | |
.slice(1) | |
.map((ticket) => ticket.split(',').map((n) => Number(n))); | |
function ruleMatches(ranges, value) { | |
return ranges.some((range) => { | |
return range[0] <= value && value <= range[1]; | |
}); | |
} | |
validTickets = nearbyTickets.filter((ticket) => | |
ticket.every((value) => rules.some((rule) => ruleMatches(rule.ranges, value))) | |
); | |
validTickets.unshift(yourTicket); | |
let index = 0; | |
while (!rules.every((rule) => rule.locations.length < 2)) { | |
const ticket = validTickets[index]; | |
if (!ticket) { | |
break; | |
} | |
rules.forEach((rule) => { | |
rule.locations = rule.locations.filter((location) => | |
ruleMatches(rule.ranges, ticket[location]) | |
); | |
}); | |
index++; | |
} | |
const foundRules = []; | |
while (rules.some((rule) => rule.locations.length === 1)) { | |
const index = rules.findIndex((rule) => rule.locations.length === 1); | |
const [foundRule] = rules.splice(index, 1); | |
foundRules.push(foundRule); | |
rules.forEach((rule) => { | |
rule.locations = rule.locations.filter((l) => l != foundRule.locations[0]); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment