Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I obtain the minimum gap between List elements?

Tags:

scala

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

like image 347
deltanovember Avatar asked Nov 11 '11 01:11

deltanovember


1 Answers

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)
like image 92
huynhjl Avatar answered Sep 29 '22 08:09

huynhjl