Representing a graph (adjacency list) with HashMap[Int, Vector[Int]] (Scala)?
adjacency-list, graph, scala, vector
Solution
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
Problem
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