How to find the second biggest number in a set of random numbers in Swift

1 Answer

0 votes
import Foundation

func findSecondMax(total: Int, rndMax: Int) -> Int? {
    var numbers: [Int] = []

    for _ in 0..<total {
        let n = Int.random(in: 1...rndMax)
        print(n)
        numbers.append(n)
    }

    let uniqueSorted = Array(Set(numbers)).sorted(by: >)
    
    return uniqueSorted.count > 1 ? uniqueSorted[1] : nil
}

let secondMax = findSecondMax(total: 10, rndMax: 100)

if let value = secondMax {
    print("The second biggest number is: \(value)")
} else {
    print("Not enough unique numbers to determine a second maximum.")
}



/*
run:

93
56
78
1
18
81
29
61
32
42
The second biggest number is: 81

*/

 



answered Oct 4, 2025 by avibootz
...