tree - How to list paths through DAG in Scala -
i have dag of words following type: hashmap[string, set[string]]
. want build collection of paths through graph. method i've written doesn't behave expect @ all:
def buildchain(wordgraph: hashmap[string, set[string]], path: listbuffer[string], accumchains: listbuffer[listbuffer[string]]): listbuffer[listbuffer[string]] = { val children = wordgraph(path.last) (word <- children) { path += word if (wordgraph.keyset.contains(word)) buildchain(wordgraph, path, accumchains) else accumchains += path } return accumchains }
when pass in graph:
map("chow" -> set("how", "cho", "cow"), "how" -> set("ho", "ow"), "cho" -> set("ho"), "cow" -> set("ow"))
i expect get:
listbuffer(listbuffer("chow", "how", "ho"), listbuffer("chow", "how", "ow"), listbuffer("chow", "cho", "ho"), listbuffer("chow", "cow", "ow"))
when start @ "chow".
instead i'm getting this:
listbuffer(listbuffer(chow, how, ho, ow, cho, ho, cow, ow), listbuffer(chow, how, ho, ow, cho, ho, cow, ow), listbuffer(chow, how, ho, ow, cho, ho, cow, ow), listbuffer(chow, how, ho, ow, cho, ho, cow, ow))
and can't figure out why. i'm sure it's simple, i'm missing right now.
here simple solution, changed little bit param types think immutable types enough:
def _buildchain(wordgraph: map[string, set[string]], path: string): list[list[string]] = { wordgraph.get(path) match { case some(w) => w.tolist.flatmap(_buildchain(wordgraph, _).map(path :: _)) case none => list(list(path)) } } def buildchain(wordgraph: map[string, set[string]], path: list[string]): list[list[string]] = path.flatmap(_buildchain(wordgraph, _)) val = _buildchain( map("chow" -> set("how", "cho", "cow"), "how" -> set("ho", "ow"), "cho" -> set("ho"), "cow" -> set("ow")), "chow") println(a) val b = buildchain( map("chow" -> set("how", "cho", "cow"), "how" -> set("ho", "ow"), "cho" -> set("ho"), "cow" -> set("ow")), list("chow", "how")) println(b)
the output is:
list(list(chow, how, ho), list(chow, how, ow), list(chow, cho, ho), list(chow, cow, ow)) list(list(chow, how, ho), list(chow, how, ow), list(chow, cho, ho), list(chow, cow, ow), list(how, ho), list(how, ow))
Comments
Post a Comment