This commit is contained in:
nim-ka
2022-11-26 00:02:42 +00:00
parent 1083edf807
commit b7ac39cb79
2 changed files with 111 additions and 70 deletions

View File

@@ -1,37 +1,78 @@
// TODO: not very efficient because i was lazy
// this one used to be a lot shorter but i made it less shoddy and slow at expense of line count
function day12(input, part2) {
let cxns = input.split("\n").map((line) => line.split("-"))
let dict = {}
let caves = []
let startId
for (let cxn of cxns) {
dict[cxn[0]] = [...(dict[cxn[0]] || []), cxn[1]]
dict[cxn[1]] = [...(dict[cxn[1]] || []), cxn[0]]
let ids = []
for (let i = 0; i < 2; i++) {
let cave = caves.find((e) => e.name == cxn[i])
if (!cave) {
caves.push(cave = {
name: cxn[i],
id: caves.length,
isStart: cxn[i] == "start",
isEnd: cxn[i] == "end",
isSmall: cxn[i] == cxn[i].toLowerCase(),
cxns: new Set()
})
if (cave.isStart) {
startId = cave.id
}
}
ids.push(cave.id)
}
caves[ids[0]].cxns.add(ids[1])
caves[ids[1]].cxns.add(ids[0])
}
let count = 0
let paths = [["start"]]
let paths = [{
cur: startId,
smallVisited: new Set(),
visitedSmallTwice: false
}]
let i = 0
while (paths.length) {
let newPaths = []
for (let path of paths) {
for (let next of dict[path.last]) {
if (next == "start") {
for (let nextId of caves[path.cur].cxns) {
let next = caves[nextId]
if (next.isStart) {
continue
}
let newPath = [...path, next]
if (newPath.count((e, i, a) => e == e.toLowerCase() && a.indexOf(e) != i) > part2) {
continue
}
if (next == "end") {
if (next.isEnd) {
count++
} else {
newPaths.push(newPath)
continue
}
let visitedSmallTwice = path.visitedSmallTwice
if (next.isSmall && path.smallVisited.has(nextId)) {
if (part2 && !visitedSmallTwice) {
visitedSmallTwice = true
} else {
continue
}
}
newPaths.push({
cur: nextId,
smallVisited: new Set(path.smallVisited).add(nextId),
visitedSmallTwice: visitedSmallTwice
})
}
}