Last active
October 25, 2023 18:43
-
-
Save MaedehJJ/a5e00c897995e1e441a2b7675323e886 to your computer and use it in GitHub Desktop.
Komoot's task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum class Sport { HIKE, RUN, TOURING_BICYCLE, E_TOURING_BICYCLE } | |
data class Summary(val sport: Sport, val distance: Int) | |
fun main() { | |
val sportStats = listOf( | |
Summary(Sport.HIKE, 92), | |
Summary(Sport.RUN, 77), | |
Summary(Sport.TOURING_BICYCLE, 322), | |
Summary(Sport.E_TOURING_BICYCLE, 656) | |
) | |
val topDistanceSport = sportStats.filter { it.sport != Sport.E_TOURING_BICYCLE }.maxByOrNull { | |
it.distance | |
} | |
println(topDistanceSport?.sport?.name ?: "The list is empty") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
sportStats
is a list, so we have some predefined functions on it likefilter
.This part of the code
sportStats.filter { it.sport != Sport.E_TOURING_BICYCLE }
is filtering the results to exclude the eBikes stats and give us a list of all the items except eBikes. Now, we can get the top distance by using themaxByOrNull
function. It will compare all the distances of the new list and return the item with the top distance, and if the list is empty, it will return null. There used to be a function calledmaxBy
, but it is now deprecated and also not safe to use.Then, in the last line, we check if the is not null, it will print the item's sport name, otherwise, it will print The list is empty