Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In scala, how can I get the count of elements that never shown in both arrays?

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.

like image 488
wwwwan Avatar asked Dec 12 '25 01:12

wwwwan


2 Answers

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
like image 149
Rex Avatar answered Dec 15 '25 13:12

Rex


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)

like image 37
Dima Avatar answered Dec 15 '25 11:12

Dima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!