我想要找到一个数组的最小和最大元素,用于理解。有没有可能用一次数组迭代来同时找到最小元素和最大元素?
我正在寻找一个不使用scala提供的array.min或max的解决方案。
发布于 2013-11-29 20:15:11
下面是一个简洁易读的解决方案,它避免了丑陋的if
语句:
def minMax(a: Array[Int]) : (Int, Int) = {
if (a.isEmpty) throw new java.lang.UnsupportedOperationException("array is empty")
a.foldLeft((a(0), a(0)))
{ case ((min, max), e) => (math.min(min, e), math.max(max, e))}
}
说明:foldLeft
是Scala中许多集合的标准方法。它允许将累加器传递给回调函数,该回调函数将为数组的每个元素调用。
有关更多详细信息,请查看scaladoc
发布于 2013-11-29 20:14:16
def findMinAndMax(array: Array[Int]) = { // a non-empty array
val initial = (array.head, array.head) // a tuple representing min-max
// foldLeft takes an initial value of type of result, in this case a tuple
// foldLeft also takes a function of 2 parameters.
// the 'left' parameter is an accumulator (foldLeft -> accum is left)
// the other parameter is a value from the collection.
// the function2 should return a value which replaces accumulator (in next iteration)
// when the next value from collection will be picked.
// so on till all values are iterated, in the end accum is returned.
array.foldLeft(initial) { ((min, max), x) =>
if (x < min) (x, max)
else if (x > max) (min, x)
else acc
}
}
发布于 2015-05-09 00:22:56
从其他答案继续-更通用的解决方案是可能的,它适用于其他集合以及Array
和其他内容以及Int
def minmax[B >: A, A](xs: Iterable[A])(implicit cmp: Ordering[B]): (A, A) = {
if (xs.isEmpty) throw new UnsupportedOperationException("empty.minmax")
val initial = (xs.head, xs.head)
xs.foldLeft(initial) { case ((min, max), x) =>
(if (cmp.lt(x, min)) x else min, if (cmp.gt(x, max)) x else max) }
}
例如:
minmax(List(4, 3, 1, 2, 5)) //> res0: (Int, Int) = (1,5)
minmax(Vector('Z', 'K', 'B', 'A')) //> res1: (Char, Char) = (A,Z)
minmax(Array(3.0, 2.0, 1.0)) //> res2: (Double, Double) = (1.0,3.0)
(也可以使用cmp.min()
和cmp.max()
更简洁地编写此代码,但前提是删除了B >: A
类型绑定,这会使函数不那么通用)。
https://stackoverflow.com/questions/20285209
复制相似问题