mirror of
https://github.com/seigler/aoc2021
synced 2025-07-26 17:06:09 +00:00
day 12
This commit is contained in:
parent
1c4a3cfcd8
commit
0a46d00d1e
4 changed files with 111 additions and 12 deletions
9
src/day12/README.md
Normal file
9
src/day12/README.md
Normal file
|
@ -0,0 +1,9 @@
|
|||
# 🎄 Advent of Code 2021 - day 12 🎄
|
||||
|
||||
## Info
|
||||
|
||||
Task description: [link](https://adventofcode.com/2021/day/12)
|
||||
|
||||
## Notes
|
||||
|
||||
...
|
90
src/day12/index.js
Normal file
90
src/day12/index.js
Normal file
|
@ -0,0 +1,90 @@
|
|||
import run from "aocrunner"
|
||||
|
||||
const parseInput = (rawInput) => rawInput.split`\n`.map((x) => x.split`-`)
|
||||
|
||||
const part1 = (rawInput) => {
|
||||
let input = parseInput(rawInput)
|
||||
input = input.concat(input.map(([from, to]) => [to, from]))
|
||||
function countPaths(history) {
|
||||
const here = history[history.length - 1]
|
||||
if (here === "end") {
|
||||
// console.log(history.join`,`)
|
||||
return 1
|
||||
}
|
||||
const exits = [
|
||||
...input.filter(
|
||||
([from, to]) =>
|
||||
from === here && (/[A-Z]+/.test(to) || !history.includes(to)),
|
||||
),
|
||||
]
|
||||
return exits.reduce(
|
||||
(acc, [from, to]) => acc + countPaths([...history, to]),
|
||||
0,
|
||||
)
|
||||
}
|
||||
return countPaths(["start"])
|
||||
}
|
||||
|
||||
const part2 = (rawInput) => {
|
||||
let input = parseInput(rawInput)
|
||||
input = input.concat(input.map(([from, to]) => [to, from]))
|
||||
function countPaths(history, haveDoubled = false) {
|
||||
const here = history[history.length - 1]
|
||||
if (here === "end") {
|
||||
// console.log(history.join`,`)
|
||||
return 1
|
||||
}
|
||||
const exits = [
|
||||
...input.filter(
|
||||
([from, to]) =>
|
||||
from === here &&
|
||||
to !== "start" &&
|
||||
(!haveDoubled || /[A-Z]+/.test(to) || !history.includes(to)),
|
||||
),
|
||||
]
|
||||
return exits.reduce(
|
||||
(acc, [from, to]) =>
|
||||
acc +
|
||||
countPaths(
|
||||
[...history, to],
|
||||
haveDoubled || (/[a-z]+/.test(to) && history.includes(to)),
|
||||
),
|
||||
0,
|
||||
)
|
||||
}
|
||||
return countPaths(["start"])
|
||||
}
|
||||
|
||||
run({
|
||||
part1: {
|
||||
tests: [
|
||||
{
|
||||
input: `start-A
|
||||
start-b
|
||||
A-c
|
||||
A-b
|
||||
b-d
|
||||
A-end
|
||||
b-end`,
|
||||
expected: 10,
|
||||
},
|
||||
],
|
||||
solution: part1,
|
||||
},
|
||||
part2: {
|
||||
tests: [
|
||||
{
|
||||
input: `start-A
|
||||
start-b
|
||||
A-c
|
||||
A-b
|
||||
b-d
|
||||
A-end
|
||||
b-end`,
|
||||
expected: 36,
|
||||
},
|
||||
],
|
||||
solution: part2,
|
||||
},
|
||||
trimTestInputs: true,
|
||||
})
|
Loading…
Add table
Add a link
Reference in a new issue