Skip to content

Instantly share code, notes, and snippets.

@MaedehJJ
Last active October 25, 2023 18:43
Show Gist options
  • Save MaedehJJ/a5e00c897995e1e441a2b7675323e886 to your computer and use it in GitHub Desktop.
Save MaedehJJ/a5e00c897995e1e441a2b7675323e886 to your computer and use it in GitHub Desktop.
Komoot's task
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")
}
@MaedehJJ
Copy link
Author

The sportStats is a list, so we have some predefined functions on it like filter.
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 the maxByOrNull 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 called maxBy, 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment