Created
December 12, 2021 21:05
-
-
Save hwartig/ce1a518b0da0ff723080ca11ca74a2f2 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
| #!/usr/bin/env node | |
| const parseInput = (input) => input.split('\n').map(line => line.split('-')).reduce((acc, [from, to]) => { | |
| if (acc[from] == undefined) { | |
| acc[from] = [to] | |
| } else | |
| acc[from].push(to) | |
| if (acc[to] == undefined) { | |
| acc[to] = [from] | |
| } else | |
| acc[to].push(from) | |
| return acc | |
| }, {}) | |
| const input = parseInput(`xx-xh | |
| vx-qc | |
| cu-wf | |
| ny-LO | |
| cu-DR | |
| start-xx | |
| LO-vx | |
| cu-LO | |
| xx-cu | |
| cu-ny | |
| xh-start | |
| qc-DR | |
| vx-AP | |
| end-LO | |
| ny-DR | |
| vx-end | |
| DR-xx | |
| start-DR | |
| end-ny | |
| ny-xx | |
| xh-DR | |
| cu-xh`) | |
| function countWaysTo(graph, secondVisitAvailable = true, currentNode = 'start', currentPath = ['start']) { | |
| return graph[currentNode].reduce((acc, node) => { | |
| if (node == 'start') return acc | |
| if (node == 'end') return acc + 1 | |
| if (node.toLowerCase() == node && currentPath.includes(node)) { | |
| if (secondVisitAvailable) { | |
| return acc + countWaysTo(graph, false, node, [...currentPath, node]) | |
| } | |
| return acc | |
| } | |
| return acc + countWaysTo(graph, secondVisitAvailable, node, [...currentPath, node]) | |
| }, 0) | |
| } | |
| console.log(countWaysTo(input, false)) | |
| console.log(countWaysTo(input)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment