From c1f6916c8ba9e0e0c67bbd810aab6c8e547c48aa Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Sun, 12 Dec 2021 13:24:41 -0500 Subject: [PATCH] tweaks --- 2021/12/part2.mjs | 53 ++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/2021/12/part2.mjs b/2021/12/part2.mjs index eaf12ba..8dfa908 100644 --- a/2021/12/part2.mjs +++ b/2021/12/part2.mjs @@ -2,53 +2,51 @@ import fs from "fs-extra"; import fp from "lodash/fp.js"; import _ from "lodash"; -import * as p1 from './part1.mjs'; +import * as p1 from "./part1.mjs"; export function solution(graph) { let paths = 0; - graph.forEachNode( node => { - graph.setNodeAttribute( node, 'nbrVisits', 0 ) - } ); + graph.forEachNode((node) => { + graph.setNodeAttribute(node, "nbrVisits", 0); + }); - const left = [ - { graph, where: 'start' } - ]; + const left = [{ graph, where: "start" }]; - while( left.length > 0 ) { + while (left.length > 0) { const position = left.shift(); - if( position.where === 'end' ) { + if (position.where === "end") { paths++; continue; } - const canVisit = (graph,node) => { - if(node === 'start') return false; - if( node === node.toUpperCase() ) return true; - const nbrVisits =graph.getNodeAttribute(node,'nbrVisits'); + const canVisit = (graph, node) => { + if (node === "start") return false; + if (node === node.toUpperCase()) return true; + const nbrVisits = graph.getNodeAttribute(node, "nbrVisits"); - if(nbrVisits ===0 ) return true; - if(nbrVisits>1) return false; - return !graph.hasAttribute('revisited'); - } - - for( const n of position.graph.neighbors(position.where) ) { - if( !canVisit( position.graph, n ) ) continue; + if (nbrVisits === 0) return true; + if (nbrVisits > 1) return false; + return !graph.hasAttribute("revisited"); + }; + for (const n of position.graph + .neighbors(position.where) + .filter((n) => canVisit(position.graph, n))) { let newGraph = position.graph; - if( n === n.toLowerCase() ) { + if (n === n.toLowerCase()) { newGraph = newGraph.copy(); - newGraph.setNodeAttribute( - n, 'nbrVisits', 1 + newGraph.getNodeAttribute(n,'nbrVisits') + newGraph.updateNodeAttribute( + n, + "nbrVisits", + fp.add(1) ); - - if( newGraph.getNodeAttribute(n,'nbrVisits') === 2 ) { - newGraph.setAttribute('revisited',n); + if (newGraph.getNodeAttribute(n, "nbrVisits") === 2) { + newGraph.setAttribute("revisited", n); } - } left.unshift({ @@ -56,7 +54,6 @@ export function solution(graph) { where: n, }); } - } return paths;