Skip to content
Snippets Groups Projects
ex01-01-seq.worksheet.sc 994 B
Newer Older
val a = Array(2, 3, 1)

a.min
myMin1(a)
myMin2(a)
myMin3(a)

myMinMax1(a)
myMinMax2(a)
myMinMax3(a)
myMinMax4(a)

def myMin1(a: Array[Int]) =
  // a.foldLeft(Int.MaxValue)((acc, v) => Math.min(acc, v))
  a.foldLeft(Int.MaxValue)(Math.min)

def myMin2(a: Array[Int]) =
  a.reduceLeft(Math.min)

def myMin3(a: Array[Int]) =
  var min = Int.MaxValue
  for v <- a do if v < min then min = v
  min

def myMinMax1(a: Array[Int]) =
  (a.min, a.max)

def myMinMax2(a: Array[Int]) =
  a.foldLeft((Int.MaxValue, Int.MinValue)) { case ((min, max), v) =>
    (if v < min then v else min, if v > max then v else max)
  }

def myMinMax3(a: Array[Int]) =
  a.foldLeft((Int.MaxValue, Int.MinValue)) { case ((min, max), v) =>
    (Math.min(min, v), Math.max(max, v))
  }

def myMinMax4(a: Array[Int]) =
  var min = Int.MaxValue
  var max = Int.MinValue
  var i = 0
  val length = a.length
  while i < length do
    val v = a(i)
    if v < min then min = v
    if v > max then max = v
    i = i + 1
  (min, max)