1
\$\begingroup\$

What would be best way achieving this? Is it possible to use Immutable map?

import scala.collection.mutable.Map

/* Convert List of Edges to mapping Node -> List of Nodes */
def create_graph(edges: Array[Array[Int]]): Map[Int, List[Int]]  = {
    val graph = Map[Int, List[Int]]();
    for (i <- 0 until edges.length) {
        val a = edges(i)(0)
        val b = edges(i)(1)
        if(graph contains a ) graph(a) = b::graph(a)
        else graph(a) = List(b)
    }
    return graph    
}
\$\endgroup\$
2
\$\begingroup\$

It is possible to achieve the same result with a scala.collection.immutable.Map:

def create_graph2(edges: Array[Array[Int]]): Map[Int, List[Int]]  = {
       // group the tuples so that a -> Array((a, b1), (a, b2), (a, b3)...)
  edges.groupBy(edge => edge(0))
       // convert the array to target list of Ints, removing duplicates
       .map{ case(key, edges) => (key, edges.map(_(1)).toSet.toList)}
}

Using the following test case:

val test1 = Array(Array(1, 2), Array(2, 3), Array(3, 4), Array(1, 5))
val result1 = create_graph(test1)
val result2 = create_graph2(test1)

The results are:

result1 = Map(2 -> List(3), 1 -> List(5, 2), 3 -> List(4))
result2 = Map(2 -> List(3), 1 -> List(2, 5), 3 -> List(4))
\$\endgroup\$
  • \$\begingroup\$ I also found that in this case mapValues() instead of map() is very convenient. \$\endgroup\$ – Ski Nov 1 '16 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.