3

I need to get the 2 max value from an array of float number i.e. one highest and one second highest.Is there any simple way of getting the along with their indexes or do I need to change the array to structure for this?

1
  • sort and get first 2? Commented Aug 1, 2016 at 11:53

9 Answers 9

6

Just sort the array and take the required value

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()

EDIT

If you want the indexes just get them like

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

If you are confused with these things just follow the normal basics as follows.

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)") 
Sign up to request clarification or add additional context in comments.

3 Comments

your code for this is good and short but it does not provide me with the indexes.
There are something wrong with your edit result will be : max:4.2->pos:4::secMax:2.0->secMaxPos:5
func secondLargest(arr: [Int]){ var max1 = -1; var max2 = -1; for item in arr { if item > max1 { max2 = max1; max1 = item }else if item > max2 { max2 = item } } print(max2) }
3

You can use enumerate() to create an array of tuples that contain (index, value) and then sort that array by value to find the two largest values:

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

Comments

1
import Algorithms

[1, 3, 5, 6, 4, 2].max(count: 2) // [5, 6]

https://github.com/apple/swift-algorithms/blob/main/Guides/MinMax.md

Comments

0
func secondLargest(arr: [Int]){
var max1 = -1;
var max2 = -1;
for item in arr {
    if item > max1 {
        max2 = max1;
        max1 = item
    }else if item > max2 {
        max2 = item
    }
}
}

Comments

-1

Try in your play gorund

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

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

print (sorted)

Comments

-1

The basic idea is to loop through the array and pick out the largest and second largest item.

Some short code that might be hard to read:

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
})

Or with more explicit variable names:

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;
        }
    }
}

Comments

-1

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

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

print(array2)

//One way

let firstMax = array2[0]

let secondMax = array2[1]

//Answer

print(firstMax)

print(secondMax)

Comments

-1

import UIKit

var array = [6,4,3,5,9,7,8,2,10]
var maxValue = 0, temp = 0, maxIndex = 0
for (index, item) in array.enumerated() {
    if (item > temp){
        maxIndex = index
    }
}
array.remove(at: maxIndex)
for (_, item) in array.enumerated() {
   if (item > maxValue){
       maxValue = item
    }
}

print("---------")
print(maxValue)
print("---------")

enter image description here

Comments

-1
var numberArray = [4.4,5.3,3.2,2.1,6.0,1.2,9.6,8.0,9.4]
var secontLargestValue = 0.0
var firstLargestValue = 0.0

for value in numberArray {
    if value > firstLargestValue {
        secontLargestValue = firstLargestValue
        firstLargestValue = value
    } else if (value > secontLargestValue && value != firstLargestValue) 
    {
        secontLargestValue = value
    }
}

print("First largest value - \(firstLargestValue)")
print("Second largest value - \(secontLargestValue)")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.