This is a simple coding exercise: find all the local maxima in given list. A local maximum is an item, which is greater than both the items immediately before and after it.
localMaxima of [2,9,5,6,1] is [9,6]
localMaxima of [2,3,4,1,5] == [4]
localMaxima of [1,2,3,4,5] == []
I wrote the this function as follows:
def localMaxima(l: List[Int]) =
(l, l.tail, l.tail.tail).zipped.toList
.filter(t => t._2 > t._1 && t._2 > t._3)
.map(_._2)
How would you write local maxima ?
scala> val l = List(2,9,5,6,1)
l: List[Int] = List(2, 9, 5, 6, 1)
scala> l.sliding(3).collect{ case a::b::c::Nil if a<b && b>c => b }.toList
res2: List[Int] = List(9, 6)
scala> val l = List(2,3,4,1,5)
l: List[Int] = List(2, 3, 4, 1, 5)
scala> l.sliding(3).collect{ case a::b::c::Nil if a<b && b>c => b }.toList
res3: List[Int] = List(4)
scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)
scala> l.sliding(3).collect{ case a::b::c::Nil if a<b && b>c => b }.toList
res4: List[Int] = List()
I would use sliding function:
def localMaxima(list : List[Int]) = list.sliding(3).foldLeft(List[Int]()){
case (seed, Seq(a, b,c)) => if(b > a && b > c) b:: seed else seed
}
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