Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Sequence difference

What would be the best way to find difference (complement) D of two sequences A and B, where D = A - B is the sequence of all objects that belong to A but not to B. For example with:

val A = Seq((1,1), (2,1), (3,1), (4,1), (5,1))
val B = Seq((1,1), (5,1))

to get:

val D = Seq((2,1), (3,1), (4,1))

Filtering of A and its subsets with B elements does not seem to be an effective solution for 'long' sequences.Any other ideas?

like image 870
zork Avatar asked Jan 09 '23 19:01

zork


1 Answers

You can use collection.SeqLike.diff method:

scala> val A = Seq((1,1), (2,1), (3,1), (4,1), (5,1))
A: Seq[(Int, Int)] = List((1,1), (2,1), (3,1), (4,1), (5,1))

scala> val B = Seq((1,1), (5,1))
B: Seq[(Int, Int)] = List((1,1), (5,1))

scala> val D = A diff B
D: Seq[(Int, Int)] = List((2,1), (3,1), (4,1))
like image 82
jarandaf Avatar answered Jan 19 '23 14:01

jarandaf