Home > Software design >  scala find the max value in a list of lists
scala find the max value in a list of lists

Time:01-29

so I'm currently learning scala and found a problem: I have a List of lists

List(
  List(8, 9, 10, 9, 8), 
  List(12, 9, 12, 8, 7), 
  List(12, 3, 12, 3, 2)
)

and want to find the max value for example:

List(12, 9, 12, 9, 8)

How can I achieve that result?

Thanks

CodePudding user response:

To find the max value at the same index in each list you can tranpose the list of lists then find the max for the transposed list.

This example straight from the Scala docs shows how tranpose works:

val xs = List(
           Set(1, 2, 3),
           Set(4, 5, 6)).transpose
 xs == List(
         List(1, 4),
         List(2, 5),
         List(3, 6))

Now do the same with your data and takes the max of the transposed lists:

val xss: List[List[Int]] = List(List(8, 9, 10, 9, 8), List(12, 9, 12, 8, 7), List(12, 3, 12, 3, 2))
                                                                                                                                                                                                                    
scala> xss.transpose.map(xs => xs.max)
val res3: List[Int] = List(12, 9, 12, 9, 8)
  •  Tags:  
  • Related