Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. ```
  2. val Sparse1 = Map(0 -> 4, 3 -> 7, 6 -> 11, 18 -> 17).withDefaultValue(0)
  3. val Sparse2 = Map(1 -> 3, 3 -> 3, 11 -> 2,18 -> 3, 20 -> 6).withDefaultValue(0)
  4. //println(Sparse2.toSeq)//to see what it is....0's missing
  5. val SparseSum = (Sparse1.toSeq ++ Sparse2.toSeq).groupBy(_._1).mapValues(_.map(_._2).sum)
  6. //println(SparseSum)
  7. val productOfValues = ((Sparse1.toSeq ++ Sparse2.toSeq).groupBy(_._1).mapValues(_.map(_._2).reduce(_*_)))
  8. //println(productOfValues)
  9. var dotProduct = 0
  10. for ((h,i) <- productOfValues) {
  11. dotProduct += i
  12. }
  13. //println(dotProduct)
  14. //If I specify some zero values, lets see what happens:
  15. val Sparse3 = Map(0 -> 4, 1 -> 0, 3 -> 7, 6 -> 11, 11 -> 0, 18 -> 17, 20 -> 0).withDefaultValue(0)
  16. val Sparse4 = Map(0 -> 0, 1 -> 3, 3 -> 3, 6 -> 0, 11 -> 2,18 -> 3, 20 -> 6).withDefaultValue(0)
  17. val productOfValues2 = ((Sparse3.toSeq ++ Sparse4.toSeq).groupBy(_._1).mapValues(_.map(_._2).reduce(_*_)))
  18. var dotProduct2 = 0
  19. for ((l, m) <- productOfValues2) {
  20. dotProduct2 += m
  21. }
  22. println(productOfValues2)
  23. println(dotProduct2)//I get 72
  24.  
  25. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement