0

I am representing a graph's adjacency list in Scala in the variable a.

        val a = new HashMap[Int, Vector[Tuple2[Int, Int]]] withDefaultValue Vector.empty
        for(i <- 1 to N) {                
            val Array(x, y, r) = readLine.split(" ").map(_.toInt)
            a(x) += new Tuple2(y, r)
            a(y) += new Tuple2(x, r)
        }

I am reading each edge in turn(x and y are nodes, while r is the cost of the edge). After reading it, I am adding it to the adjacency list.

However, when adding the Tuples containing a neighbouring node and a cost to the HashMap I get:

Solution.scala:17: error: type mismatch;
 found   : (Int, Int)
 required: String
                a(x) += new Tuple2(y, r)

I don't understand why it wants String. I haven't specified String anywhere.

2 Answers 2

3

+= is the operator for concatenating to a String.

You would probably want to do something like: a.update(x, a.getOrElse(x, Vector()) :+ (x, r)).

Sign up to request clarification or add additional context in comments.

Comments

2

Also, you are writing Java code in Scala. It compiles, but amounts to abuse of the language :/

Consider doing something like this next time:

val a = Range(1, N)
   .map { _ => readline.split(" ").map (_.toInt) }
   .flatMap { case Array(x, y, r) => 
       Seq(x -> (y, r), y -> (x, r)) 
   }
   .groupBy(_._1)
   .mapValues { _.map ( _._2) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.