Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 查找排序列表中小于给定数字的最大数字_Scala_List - Fatal编程技术网

Scala 查找排序列表中小于给定数字的最大数字

Scala 查找排序列表中小于给定数字的最大数字,scala,list,Scala,List,假设我需要在排序列表中找到小于给定数字y的最大数字。 比如说 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) 您将如何实现此功能?def findLargest(xs:Lis

假设我需要在排序列表中找到小于给定数字
y
的最大数字。
比如说

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)
您将如何实现此功能?

def findLargest(xs:List[Int],y:Int):Option[Int]={
def findLargest(xs: List[Int], y: Int): Option[Int] = {
    xs.takeWhile(_ < y).lastOption
}
xs.takeWhile(
由于列表已排序:

def findLargest(xs: List[Int], y: Int): Option[Int] = xs.reverse.find(_ < y)
def findLargest(xs:List[Int],y:Int):Option[Int]=xs.reverse.find(uy
您可以定义为

   def findLargest(xs: List[Int], y: Int): Option[Int] = xs.filter(x => x < y).sorted.lastOption
def findLargest(xs:List[Int],y:Int):Option[Int]=xs.filter(x=>x
使用Collect

假设列表按升序排序

def findLargest(xs: List[Int], y: Int): Option[Int] = 
  xs.reverse.collect { case x if x < y => x }.headOption
def findLargest(xs:List[Int],y:Int):选项[Int]=
xs.reverse.collect{case x if xx}.headOption
Scala REPL

scala> def findLargest(xs: List[Int], y: Int): Option[Int] =
     |       xs.reverse.collect { case x if x < y => x }.headOption
findLargest: (xs: List[Int], y: Int)Option[Int]

scala> findLargest(List(1, 2,  3), 1)
res3: Option[Int] = None

scala> findLargest(List(1, 2,  3), 2)
res4: Option[Int] = Some(1)

scala> findLargest(List(1, 2,  3), 3)
res5: Option[Int] = Some(2)
scala>deffindlargest(xs:List[Int],y:Int):选项[Int]=
|xs.reverse.collect{case x if xx}.headOption
findLargest:(xs:List[Int],y:Int)选项[Int]
scala>findLargest(列表(1,2,3,1)
res3:选项[Int]=无
scala>findLargest(列表(1,2,3,2)
res4:Option[Int]=Some(1)
scala>findLargest(列表(1,2,3,3))
res5:Option[Int]=Some(2)

到目前为止,您尝试了什么?在实现此功能时遇到了什么问题?如果列表未按
val xs=list(1,2,7,4,8)排序,则不会给出正确的输出