Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter condition using filtered value

I would like to filter collection, so distance between adjacent elements would be at least 5.

So List(1, 2, 3, 4, 5, 6, 7, 11, 20) will become List(1, 6, 11, 20).

Is it possible to achieve in one pass using filter? What would be scala-way?

like image 545
user482745 Avatar asked Dec 16 '22 14:12

user482745


1 Answers

How about this one-liner:

scala> l.foldLeft(Vector(l.head)) { (acc, item) => if (item - acc.last >= 5) acc :+ item else acc }

res7: scala.collection.immutable.Vector[Int] = Vector(1, 6, 11, 20)
like image 149
Ryan LeCompte Avatar answered Jan 03 '23 03:01

Ryan LeCompte