Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: the most effective way to find first index of minimum element in some list of some objects

Tags:

kotlin

I have some list of instances of some custom class:

data class Flight(val duration: Int)

For example:

val flights = listOf(Flight(10), Flight(5), Flight(5), Flight(15), Flight(20))

How to most effectively find first index of the minimum element in this list? In that case the first index of min element is 1, because flights[1].duration = 5.

like image 524
grolegor Avatar asked Mar 20 '19 11:03

grolegor


People also ask

How do you use Kotlin indexOf?

indexOf() to Check if Element is in List. If the element is present in the list, then list. indexOf(element), will return a non-negative integer, else it returns -1. We can use this behavior to check if element is present in the list or not.

How to get element from set in Kotlin?

The example presents Kotlin Set indexing operations. An element is retrieved with the elementAt method. The method takes an index of the element to be retrieved as a parameter. The indexOf returns the index of the first occurrence of the word in the set.


Video Answer


2 Answers

Something like this would be "most efficient", I guess:

var min: Pair<Int, Flight>? = null
for (f in flights.withIndex()) {
    if (min == null || min.second.duration > f.value.duration) min = f.index to f.value
}

And this one does basically the same and looks much better:

flights.withIndex().minBy { (_, f) -> f.duration }?.index
like image 186
s1m0nw1 Avatar answered Oct 21 '22 23:10

s1m0nw1


With minBy() to get the list item with the minimum duration
and then indexOf() to get its index:

val index = flights.indexOf(flights.minBy { it.duration })

For just 1 scan of the list, you can do a classic loop:

var index = if (flights.isEmpty()) -1 else 0
flights.forEachIndexed { i, flight ->
    if (flight.duration < flights[index].duration) index = i
}
like image 6
forpas Avatar answered Oct 21 '22 21:10

forpas