FredoFredo
FredoFredo

Reputation: 43

iOS - selecting second lowest number in integer array

Let's say I have an array of numbers:

let numbers: [Int] = [1,2,3,4,5,6,7,8]

I want to pick out the second lowest number in that array but I don't want to use an index, I know you can pick the lowest and highest integer using min/maxElement dot notation so how would I get the second lowest or the second highest?

Upvotes: 2

Views: 2233

Answers (5)

Navroz Huda
Navroz Huda

Reputation: 1

func getSecondSmallest(arr:[Int])->Int{
var minNumber = arr.last ?? Int.max
var secondSmallest = arr.last ?? Int.max
for i in arr{
    if minNumber > i {
        minNumber = i
    }else if i > minNumber && secondSmallest > i{
        secondSmallest = i
    }
}
return secondSmallest

}

Upvotes: 0

Khalid-R
Khalid-R

Reputation: 1

// how to get the second lowest number in an integer Array

func secondLowest(arr: [Int]) -> Int {
    let sortedArr = arr.sorted()
    return sortedArr[1]
}

print(secondLowest(arr: [1,8,100,4,5,6,7,2,212])) // 2

Upvotes: 0

OOPer
OOPer

Reputation: 47896

A direct implementation: (as Sulthan suggested?)

func secondMax(numbers: [Int]) -> Int {
    let (_, second) = numbers.reduce((Int.min, Int.min)) {(max2: (first: Int, second: Int), value: Int) in
        if value > max2.first {
            return (value, max2.first)
        } else if value > max2.second {
            return (max2.first, value)
        } else {
            return max2
        }
    }
    return second
}
print(secondMax([1,2,3,4,5,6,7,8])) //->7
print(secondMax([1,1,2,3,4,4])) //->4
print(secondMax([5,5,6,1,2,3,4])) //->5
print(secondMax([5,6,6,1,2,3,4])) //->6

Upvotes: 0

Khundragpan
Khundragpan

Reputation: 1960

As per OP comment that second max, min will be the max and min of array in case if redundancy. I have updated the approach.

var numbers: [Int] = [1,1,2,3,4,4] // or [1,2,3,4,5,6,7,8]
let maxCount = numbers.filter({$0 == numbers.max()}).count
let minCount = numbers.filter({$0 == numbers.min()}).count

let secondHighest = numbers.filter(){
    maxCount > 1 ? $0 == numbers.max() :  $0 < numbers.max()
}.last
// prints 4 for [1,1,2,3,4,4] and 7 for [1,2,3,4,5,6,7,8]

let secondLowest = numbers.filter(){
    minCount > 1 ? $0 == numbers.min() :  $0 > numbers.min()
}.first
// prints 1 for [1,1,2,3,4,4] and 2 for [1,2,3,4,5,6,7,8]

Upvotes: 2

Code Different
Code Different

Reputation: 93181

(1) Find the lowest value; (2) Remove that value; (3) Find min of the remaining:

let numbers: [Int] = [1,2,3,4,5,6,7,8]

var lowest = numbers.minElement()!
var secondLowest = numbers.filter { $0 > lowest }.minElement()

secondLowest is an optional because in case all values in your array are identical, there is really no "second lowest"

Upvotes: 1

Related Questions