Filter Status Using a Filtered Value

I would like to filter the collection, so the distance between adjacent elements should 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 a filter? What will be scala -way?

+4
source share
2 answers

Try with foldLeft() :

 val input = List(1, 2, 3, 4, 5, 6, 7, 11, 20) input.tail.foldLeft(List(input.head))((out, cur) => if(cur - out.head >= 5) cur :: out else out ).reverse 

If this is not obvious:

  • The algorithm starts with the first element (maybe you need processed faces) in the output collection

  • Iterates over all remaining elements from input . If the difference between this ( cur ) element and the first input element is greater than or equal to 5 , add to input . Otherwise, skip and continue

  • input was created by adding and exploring head to improve performance. .reverse required at the end

This is basically how you should implement this for real, but with more concise syntax.

+5
source

How about this one line interface:

 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) 
+7
source

All Articles