Michael Michael -4 years ago 69
Scala Question

Find the largest number that is lesser than a given number in a sorted list

Suppose I need to find the largest number lesser than given number

y
in a sorted list.

For instance

def findLargest(xs: List[Int], y: Int): Option[Int] = ???

val xs = List(1, 2, 4, 8)
findLargest(xs, 5) // should return Some(4)
findLargest(xs, 1) // None
findLargest(xs, 9) // Some(8)


How to implement this function ?

Answer Source
def findLargest(xs: List[Int], y: Int): Option[Int] = {
    xs.takeWhile(_ < y).lastOption
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download