Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Maxima of List in Scala

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 ?

like image 388
Michael Avatar asked Nov 28 '22 16:11

Michael


2 Answers

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()
like image 164
Marth Avatar answered Dec 05 '22 14:12

Marth


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
}
like image 36
grotrianster Avatar answered Dec 05 '22 13:12

grotrianster