main
Yanick Champoux 2021-12-12 13:24:41 -05:00
parent 8de4107b95
commit c1f6916c8b
1 changed files with 25 additions and 28 deletions

View File

@ -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;