如何从swift中的浮点数数组中获得前2个最大值?

时间:2016-08-01 11:49:08

标签: ios arrays swift

我需要从一个浮点数的数组中得到2个最大值,即一个最高和一个最高。是否有任何简单的方法来获取它们的索引或者我是否需要将数组更改为此结构?

5 个答案:

答案 0 :(得分:5)

只需对数组进行排序并获取所需的值

var array1 = [2.1, 2.2, 2.5, 3.0, 4.2, 2]

var array2 = array1.sort(){ $0 > $1}

//One way 
let firstMax = array2[0]
let secondMax = array2[1]

//Second way
let firstMax = array2.removeFirst()
let secondMax = array2.removeFirst()

修改

如果你想让索引像

那样
let maxPos = array1.indexOf(firstMax)
let secMaxPos = array1.indexOf(secondMax)

如果您对这些事情感到困惑,请按照以下正常基础进行操作。

var max = -1.0, maxPos = -1, secMax = -1.0, secMaxPos = -1
for (index, value) in array1.enumerate() {
    if value > max {
        max = value
        maxPos = index
    } else if value > secMax {
        secMax = value
        secMaxPos = index
    }
}
print("max:\(max)->pos:\(maxPos)::secMax:\(secMax)->secMaxPos:\(secMaxPos)") 

答案 1 :(得分:2)

您可以使用enumerate()创建包含(index,value)的元组数组,然后按值对该数组进行排序,以找到两个最大的值:

let arr: [Float] = [1.2, 3.14, 1.609, 2.718, 0.3]

// Create an array of (index, value) tuples sorted by value
// in decreasing order
let result = arr.enumerate().sort { $0.1 > $1.1 }
print(result)
[(1, 3.1400001), (3, 2.71799994), (2, 1.60899997), (0, 1.20000005), (4, 0.300000012)]
let (topIndex, top) = result[0]
print("top = \(top), index = \(topIndex)")
top = 3.14, index = 1
let (secondIndex, second) = result[1]
print("second = \(second), index = \(secondIndex)")
second = 2.718, index = 3

答案 2 :(得分:0)

尝试玩你的游戏

var item = [2.01,3.95,1.85,2.65,1.6]

var sorted = item.sort({$ 0> $ 1})

打印(已排序)

答案 3 :(得分:0)

基本思想是循环遍历数组并选出最大和第二大项。

一些可能难以阅读的简短代码:

let myFloatArray : [Float] = ...
let top2 = myFloatArray.enumerated().reduce(((-1, Float.nan), (-1, Float.nan)), combine: { t, v in
    // Check if value is larger than first item in tuple
    if (!(v.1 <= t.0.1)) {
        // Check if value is larger than second item in tuple
        if (!(v.1 <= t.1.1)) {
            // Return with new value as largest
            return (t.1, v)
        } else {
            // Return with new value as next largest
            return (v, t.1)
        }
    }
    // Return old result
    return t
})

或者使用更明确的变量名称:

var largestIndex = -1;
var largestValue = Float.nan;
var secondLargestIndex = -1;
var secondLargestValue = Float.nan;
for index in 0..<myFloatArray.count {
    let value = myFloatArray[index];
    if (!(value <= secondLargestValue)) {
        if (!(value <= largestValue)) {
            secondLargestValue = largestValue;
            secondLargestIndex = largestIndex;
            largestValue = value;
            largestIndex = index;
        } else {
            secondLargestValue = value;
            secondLargestIndex = index;
        }
    }
}

答案 4 :(得分:0)

var array1 = [1,2,3,4,5]

var array2 = array1.sorted(){ $0 > $1}

打印(数组2)

//一种方式

让 firstMax = array2[0]

让 secondMax = array2[1]

//答案

打印(firstMax)

打印(secondMax)