Representing a graph (adjacency list) with HashMap[Int, Vector[Int]] (Scala)?

守給你的承諾、 提交于 2019-12-23 17:29:04

问题


I was wondering how (if possible) I can go about making an adjacency list representation of a (mutable) graph via HashMap[Int, Vector[Int]]. HashMap would be mutable of course.

Currently I have it set as HashMap[Int, ArrayBuffer[Int]], but the fact that I can change each cell in the ArrayBuffer makes me uncomfortable, even though I'm fairly certain I'm not doing that. I would use a ListBuffer[Int] but I would like fast random access to neighbors due to my need to do fast random walks on the graphs. A Vector[Int] would solve this problem, but is there anyway to do this?

To my knowledge (tried this in the REPL), this won't work:

scala> val x = new mutable.HashMap[Int, Vector[Int]]
x: scala.collection.mutable.HashMap[Int,Vector[Int]] = Map()

scala> x(3) = Vector(1)

scala> x(3) += 4 // DOES NOT WORK

I need to be able to both append to it at any time and also access any element within it randomly (given the index). Is this possible?

Thanks! -kstruct


回答1:


Using the Vector:

x += 3 -> (x(3) :+ 4)  //x.type = Map(3 -> Vector(1, 4))

You might notice that this will fail if there's no existing key, so you might like to set up your map as

val x = new mutable.HashMap[Int, Vector[Int]] withDefaultValue Vector.empty


来源:https://stackoverflow.com/questions/10358265/representing-a-graph-adjacency-list-with-hashmapint-vectorint-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!