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

1 Answer

0 votes
import kotlin.random.Random

fun findSecondMax(total: Int, rndMax: Int): Int? {
    val numbers = List(total) {
        val n = Random.nextInt(1, rndMax + 1)
        println(n)
        n
    }

    val uniqueSorted = numbers.toSet().sortedDescending()
    
    return uniqueSorted.getOrNull(1)
}

fun main() {
    val secondMax = findSecondMax(10, 100)
    if (secondMax != null) {
        println("The second biggest number is: $secondMax")
    } else {
        println("Not enough unique numbers to determine a second maximum.")
    }
}



/*
run:

34
76
62
70
4
3
56
93
75
90
The second biggest number is: 90

*/

 



answered Oct 4, 2025 by avibootz
...