Last active
April 23, 2018 18:22
-
-
Save cauefcr/2946a51eaefa3ac6083b90730679cc7b to your computer and use it in GitHub Desktop.
generate all paths from a DAG
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
// https://bl.ocks.org/cjrd/raw/6863459/ | |
// draw your DAG, download the json | |
// authors: Cauê Felchar, José Henrique Roquette | |
g = <your json> | |
dag_all_paths = function(g,start,end){ | |
dict = new Map(); | |
dictname = new Map(); | |
for(let i = 0; i < g.nodes.length; i++){ | |
dict[g.nodes[i].id] = i; | |
dictname[g.nodes[i].title] = i; | |
} | |
g.look = function(e){ | |
return g.nodes[e]; | |
}; | |
g.name = function(e){ | |
return g.look(e).title; | |
}; | |
g.name2index = function(n){ | |
return dictname[n]; | |
} | |
g.vizinho = function(){ | |
g.viz = []; | |
for(let i = 0; i < g.nodes.length; i++){ | |
g.viz.push([]); | |
} | |
for(let i = 0; i < g.edges.length; i++){ | |
g.viz[dict[g.edges[i].source]].push(dict[g.edges[i].target]); | |
} | |
}; | |
path = []; | |
function caminhos(grafo,inicial,ultimo,estado){ | |
estado.push(inicial); | |
if(grafo.viz[inicial].length === 0){ | |
path.push(estado.map(g.name)); | |
} | |
grafo.viz[inicial].forEach(function(el){ | |
caminhos(grafo,el,ultimo,estado.slice(0)); | |
}); | |
} | |
g.vizinho(); | |
caminhos(g,g.name2index(start),g.name2index(end),[]); | |
return path; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment