简体   繁体   中英

How to find multiple maximum arguments in a scala list

Good evening, How to find multiple maximum arguments in a scala list:

val finale = list(2,2,3,4,6,6);    
val indexMax = finale.zipWithIndex.maxBy(_._1)._2

Here I can find only the argument of one maximum (6), but I want to find the two last (6) values

Sightly modified from Rajkumar's comment, this snippet returns a List with the indexes of the maximum elements in a list.

def findMaximumIndices(list: List[Int]): List[Int] =
  list.zipWithIndex.groupBy(_._1).maxBy(_._1)._2.map(_._2)

val list = List(2,2,3,4,6,6)
val maximumIndices = findMaximumIndices(list)
// maximumIndices: List[Int] = List(4, 5)

It is quite obscure by the excessive use of tuple accessors with underscore anonymous functions notation. (_._1).

How about a simple foldLeft?

  finale.foldLeft(Seq.empty[Int]) {
    case (max @ head :: _, element) if element == head => max :+ element
    case (max @ head :: _, element) if element > head => Seq(element)
    case (Nil, element) => Seq(element)
    case (max, _) => max
  }

This can be done even more efficient by not using Seq.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM