Home > Software design >  Scala program that gives me smallest and largest number from an Array
Scala program that gives me smallest and largest number from an Array

Time:03-04

I am looking for a scala code that gives me new Array that contains the smallest and largest number in myArr.

I am able to write the below code . How do i write it in a single function

scala> val myArr = Array(1,5,3)
 myArr: Array[Int] = Array(1, 5, 3)

 scala> myArr.reduce((a,b) => if(a>b)a else b)
 res0: Int = 5

 scala> myArr.reduce((a,b) => if(a<b)a else b)
 res1: Int = 1

Expected output : Array(1,5)

CodePudding user response:

val myArr = Array(1,5,3)

val result = myArr.foldLeft(List.empty[Int]){
 case (min :: max :: _, value) if value < min => List(value, max) // lower than the minimun
 case (min :: max :: _, value) if value > max => List(min, value) // greater than the maximun
 case (Nil, value) => List(value, value) // first value
 case (l, _) => l // the final list doesn't need to be updated
}

you can check it here https://scastie.scala-lang.org/XLE8VAKTRhWbl0JFrjGgnw It uses the list to have better pattern matching.

  • Related