-4

Now there are two thus tuples.

1st tuple:((A,1),(B,3),(D,5)......)
2nd tuple:((A,3),(B,1),(E,6)......)

And the function is to merge those two tuples to this.

((A,1,3),(B,3,1),(D,5,0),(E,0,6)......)

If the first tuple contains a key that is not in the second tuple, set the value to 0, and vice versa. How could I code this function in scala?

Shaido
  • 27,497
  • 23
  • 70
  • 73
Wangkkkkkk
  • 15
  • 5

2 Answers2

0

Lets say you get the input in the format

val tuple1: List[(String, Int)] = List(("A",1),("B",3),("D",5),("E",0))
val tuple2: List[(String, Int)] = List(("A",3),("B",1),("D",6))

You can write a merge function as

def merge(tuple1: List[(String, Int)],tuple2: List[(String, Int)]) =
{
  val map1 = tuple1.toMap
  val map2 = tuple2.toMap

  map1.map{ case (k,v) =>
    (k,v,map2.get(k).getOrElse(0))
  }
}

On calling the function

merge(tuple1,tuple2)

You will get the output as

res0: scala.collection.immutable.Iterable[(String, Int, Int)] = List((A,1,3), (B,3,1), (D,5,6), (E,0,0))

Please let me know if that answers your question.

Chaitanya
  • 3,590
  • 14
  • 33
0
val t1= List(("A",1),("B",3),("D",5),("E",0))
val t2= List(("A",3),("B",1),("D",6),("H",5))
val t3 = t2.filter{ case (k,v) => !t1.exists(case (k1,_) => k1==k)) }.map{case (k,_) => (k,0)}
val t4 = t1.filter{ case (k,v) => !t2.exists{case (k1,_) => k1==k} }.map{case (k,_) => (k,0)}
val t5=(t1 ++ t3).sortBy{case (k,v) => k}
val t6=(t2 ++ t4).sortBy{case (k,v) => k}
t5.zip(t6).map{case ((k,v1),(_,v2)) => (k,v1,v2) }
res: List[(String, Int, Int)] = List(("A", 1, 3), ("B", 3, 1), ("D", 5, 6), ("E", 0, 0), ("H", 0, 5))

In terms of what's happening here t3 and t4 - find the missing value in t1 and t2 respectively and add them with a zero value t5 and t6 sort the unified list (t1 with t3 and t2 with t4). Lastly they are zipped together and transformed to the desired output

Arnon Rotem-Gal-Oz
  • 25,469
  • 3
  • 45
  • 68