I need to write a code snippet that would compare multiple arrays and produce the set that match the data in those arrays, produce the data set only in array A, but not in array B,C,D,in array B but not in A,C,D, being able to handle any number of arrays (i.e. dynamically looped). The code should utilize anonymous functions in Scala (i.e. not like a regular array looping like in Java).
Sounds like homework to me. By far the easiest way to do this is to throw the contents of array A into a Set
and use the remove operation. This would be O(n) where n = \sum { |A|, |B|, |C|, ... }. The following solution works for arbitrary Iterable
, not just Array
:
def compareArrays[A](arrs: List[Iterable[A]]) = arrs match {
case a :: tail => {
val set = a.foldLeft(Set[A]()) { _ + _ }
tail.foldLeft(set) { _ -- _ }
}
case Nil => Nil
}