3

for example, i have array a Array[Int] = Array(1, 1, 2, 2, 3) array b Array[Int] = Array(2, 3, 4, 5) i'd like to count how many elements that only shown in a or b. in this case, it's (1, 1, 4, 5), so the count is 4.

I tried diff, union, intersect, but I couldn't find a combination of them to get the result I want.

wwwwan
  • 407
  • 1
  • 4
  • 12

2 Answers2

5

I think you can try something like this one but this is not good approach, still this will do the trick.

a.filterNot(b contains).size + b.filterNot(a contains).size
Rex
  • 558
  • 2
  • 9
4

Same idea as the other answer, but linear time:

 a.iterator.filterNot(b.toSet).size + b.iterator.filterNot(a.toSet).size

(.iterator to avoid creating intermediate collections)

Dima
  • 39,570
  • 6
  • 44
  • 70