1. Overview
In our daily work, comparing and determining the largest value among a set of numbers is a common task.
In this tutorial, we’ll explore finding the largest among three numbers in Kotlin. Further, we’ll extend the topic and discuss the solution of finding the largest from the given n numbers.
2. Introduction to the Problem
Finding the largest number from three or even n numbers isn’t a hard problem. The Kotlin standard library offers some convenient functions to do the job. We’ll see them shortly.
But, before we look at the usage of those functions, we’ll start by crafting our own solution with some elegant Kotlin features. This can be helpful for newcomers to the Kotlin world.
We’ll take Int as the example in this tutorial. However, the solutions can be adapted to all subtypes of Number.
Next, let’s dive into the code.
3. Crafting Our Solutions
Given three numbers, we can take each one from the three numbers and compare it to the other two to decide if it’s the largest. If the first two numbers aren’t the largest, then the third one must be the answer:
val a = 42
val b = 100
val c = -42
val result = if (a >= b && a >= c) {
a
} else if (b >= a && b >= c) {
b
} else {
c
}
assertEquals(100, result)
The implementation is based on if-else. The code is pretty straightforward to understand. However, it’s worth noting that Kotlin’s if is an expression. So, it returns a value. That’s why we wrote val result = if (…) {…} in the code.
Following the same algorithm, we can also change the if-else expression to the when expression to make the code easier to read:
val (a, b, c) = listOf(42, 100, -42)
val result = when {
a >= b && a >= c -> a
b >= a && b >= c -> b
else -> c
}
assertEquals(100, result)
The algorithm solves the problem. In the worst case, we need to compare four times to find the result from three numbers. Imagine that we have n numbers. This algorithm may perform (n-1) * (n-1) times comparison. So, its time complexity will be O(n^2).
Another idea to solve the problem is finding the larger number from the first two and comparing the larger one with the third number. So, we only need two comparisons to find the answer. If we have n numbers, this approach’s time complicity is O(n).
Now, let’s implement it:
val (a, b, c) = listOf(42, 100, -42)
val maxOfAB = if (a >= b) a else b
val result = if (c >= maxOfAB) c else maxOfAB
assertEquals(100, result)
In the code above, we used Kotlin’s destructing declaration to assign three variables (a, b, and c) in one shot.
After discussing our own algorithms and implementations, let’s see how the Kotlin standard library can help us solve the problem.
4. Using the math.max() Method
The max() function from the kotlin.math package can return the greater from two number arguments. We can call this function twice to get the largest value from three numbers:
val (a, b, c) = listOf(42, 100, -42)
val result = max(max(a, b), c)
assertEquals(100, result)
5. The n Numbers Scenario
If we’re given n numbers, usually they are in a Collection, such as a List. Kotlin offers a rich set of handy functions that allow us to work with a collection easily.
For example, finding the largest value in a list is as simple as calling list.max():
val nNumbers = listOf(42, 100, -42, 20, 43, -2, 103, 420)
val result = nNumbers.max()
assertEquals(420, result)
However, we should note that if the list is empty, max() raises NoSuchElementException:
assertThrows<NoSuchElementException> { emptyList<Int>().max() }
Therefore, we should employ maxOrNull() if our list can be empty. It returns null for an empty list:
val possibleMax = emptyList<Int>().maxOrNull()
assertNull(possibleMax)
6. Conclusion
In this article, we implemented two algorithms to the largest from three numbers. Further, we discussed their performance.
Furthermore, we demonstrated the application of list.max() and list.maxOrNull() functions to identify the maximum value from a collection of n numbers.
As always, the complete source code for the examples is available over on GitHub.