Vector(4,8), "W2" -> Vector(5" /> Vector(4,8), "W2" -> Vector(5" /> Vector(4,8), "W2" -> Vector(5"/>

Inserting elements in a specific positions in the existing array

77 Views Asked by At

I have a List and Map as below,

 val exampleList = List("A","B","C","D","E","A","L","M","N")
 val exampleMap = Map("W1" -> Vector(4,8),
                      "W2"  -> Vector(5),
                      "W3" -> Vector(9))

So I need to add all the letters in the exampleMap to the exampleList according to the values (indexes that should take places in the exampleList) that in the exampleMap. So the final output should be something like this val result = List("A","B","C","D","W1","E","W2","A","L","M","W1","N","W3")

I tried several ways using foldLeft as well as using flatMap but still not get any luck.

1

There are 1 best solutions below

3
Johny T Koshy On

I am making two assumptions

  1. There won't be any repetition. For eg: "W4" -> Vector(4).
  2. At the most one value is to be placed beyond the size.

To solve, I would first change exampleMap as follows,

//Map(4 -> W1, 8 -> W1, 5 -> W2, 9 -> W3)
val modifiedExampleMap = exampleMap.flatMap { case (k, v) =>
  v.map(_ -> k)
}

and then use it to create the final list.

exampleList.view.zipWithIndex.foldLeft(List.empty[String]) {
  case (acc, (elem, index)) =>
    modifiedExampleMap.get(index + 1) match {
      case Some(value) => value :: elem :: acc
      case None => elem :: acc
    }
}.reverse