Array of array subtraction in scala
scala
Solution
If you mean you want to subtract B from A for every matching key, and if the difference is 0, ignore it, then do this:
val a = Array((1,2), (2,3), (4,1))
val b = Array((1,1), (2,3))
val bMap = b.toMap
a.map{ case (k,v) => (k, v - bMap.getOrElse(k,0)) }.filter(_._2 != 0)
// Array((1,1), (4,1))
This procedure converts `b` to a map for easy lookup. Then we traverse `a` and, for each element, subtract `b`'s value for that key (or 0 if it's not there). Finally, we remove any entries in the result that have a value of 0.
Problem
I'm learning the ropes of Scala, and am wondering if there is an easy way to do array subtraction. Let's say I have two arrays where elements are of the form (K,V): ``` A: Array((1,2), (2,3), (4,1)) B: Array((1,1), (2,3)) ``` I would like to get ``` A - B: Array((1,1), (4,1)) ``` The corresponding keys should subtract. Any help is appreciated. Thanks in advance! Edit: Seems like the word "subtract" is confusing. What I wish to do is to subtract values of matching keys in (K, V) pairs in the arrays.