Max and min in an array of Float in Swift

后端 未结 5 838
悲哀的现实
悲哀的现实 2021-01-14 17:57

According to this answer, to obtain the maximum of an array we can do:

let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, { max($0, $1) })


        
相关标签:
5条回答
  • 2021-01-14 18:31

    Swift 2:

    var graphPoints:[Int] = [4, 2, 6, 4, 5, 8, 3]
    let maxValue = graphPoints.maxElement()
    
    0 讨论(0)
  • 2021-01-14 18:33

    Just use the first array element as the initial value:

    let numMax = floats.reduce(floats[0], { max($0, $1) })
    

    but of course you need to check that the floats array is not empty before doing it.

    0 讨论(0)
  • 2021-01-14 18:42

    The solution given here https://stackoverflow.com/a/24161004/1187415 works for for all sequences of comparable elements, therefore also for an array of floats:

    let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
    let numMax = maxElement(floats)
    

    maxElement() is defined in the Swift library as

    /// Returns the maximum element in `elements`.  Requires:
    /// `elements` is non-empty. O(countElements(elements))
    func maxElement<R : SequenceType where R.Generator.Element : Comparable>(elements: R) -> R.Generator.Element
    
    0 讨论(0)
  • 2021-01-14 18:49

    You can use -FLT_MAX which returns minimum magnitude of Float and used for same purpose

    let numMax = floats.reduce(-FLT_MAX, { max($0, $1) })
    

    For Double array you can use -DBL_MAX

    If you want maximum magnitude value of Float use FLT_MAX.FLT_MIN is Minimum representable postive floating-point number.

    0 讨论(0)
  • 2021-01-14 18:51

    Swift 4 has a .max() method for Array<Float>.

    Example:

    let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
    let max = floats.max()
    

    Note: max() returns an optional so there's a chance it could come back nil.

    0 讨论(0)
提交回复
热议问题