For example suppose I have a sorted list
val sorted = List(1, 5, 15, 37, 39, 42, 50)
The smallest gap is (39-37)=2. How would I obtain this result? I have been looking at foldLeft I get the feeling it is similar to what I need but not quite the right thing
val sorted = List(1, 5, 15, 37, 39, 42, 50)
sorted match {
case Nil => None
case List(a) => None
case l => Some(l.sliding(2).map{case Seq(a, b) => math.abs(a - b)}.min)
}
// res1: Option[Int] = Some(2)
sliding
returns an iterator, so that should only traverse the list once.
If you are interested to find which two elements have the smallest gap, you can also use minBy. So here is another variation, just for fun.
sorted.view.zip(sorted.tail).minBy(t => math.abs(t._1 - t._2))
// res4: (Int, Int) = (37,39)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With