Advertisement
ZivkicaI

MinMaxAnotherWay

Dec 3rd, 2019
590
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.40 KB | None | 0 0
  1. val array = Array(3,4,62,8,9,2,1)
  2. if(array.isEmpty) throw new IllegalArgumentException // Just so we can safely call array.head
  3.  
  4. val (minimum, maximum) = array.foldLeft((array.head, array.head)) {  // We start of with the first element as min and max
  5.   case ((min, max), next) =>
  6.     if(next > max) (min, next)
  7.     else if(next < min) (next, max)
  8.     else (min, max)
  9. }
  10.  
  11. println(minimum, maximum)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement