1

Given this function

  def makeAdjacencyList(edgeList: Seq[(String, String)]): Map[String, Seq[String]] = {
    val emptyMap = Map[String, Seq[String]]().withDefaultValue(Seq[String]())

    edgeList.foldLeft(emptyMap) {
      case (acc, curr) => {
        acc + (curr._1 -> (acc(curr._1) :+ curr._2))
        acc + (curr._2 -> (acc(curr._2) :+ curr._1))
      }
    }
  }

It takes in a edgeList of an undirected graph, for example:

Vector((S1,E1), (S1,D1), (S2,E2), (S2,D1), (S3,E1), (S3,D2))

The function however gives an output of

[E1 -> [S1, S3], D1 -> [S1, S2], E2 -> [S2], D2 -> [S3]]

but I was expecting an output of

[S1 -> [E1, D1], S2 -> [E2, D1], S3 -> [E1], E1 -> [S1, S3], D1 -> [S1, S2], E2 -> [S2], D2 -> [S3]]

It seems like the first line of the foldLeft (acc + (curr._1 -> (acc(curr._1) :+ curr._2))) is being ignored and I am not quite sure why.

0

1 Answer 1

3

Both lines of code in the case block produces a result, but only the 2nd result is returned and becomes the next acc value.

This would fix it.

edgeList.foldLeft(emptyMap) {
  case (acc, curr) =>
    acc + (curr._1 -> (acc(curr._1) :+ curr._2)) +
          (curr._2 -> (acc(curr._2) :+ curr._1))
}

Here, on the other hand, is a different approach to achieve the desired output.

def makeAdjacencyList(edgeList: Seq[(String,String)]): Map[String,Seq[String]] =
  edgeList.flatMap(edge => Seq(edge, edge.swap))
          .groupMap(_._1)(_._2)
Sign up to request clarification or add additional context in comments.

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.