Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Kotlin have something similar to an argmax method?

So let's say I have a numpy array like this:

import numpy as np
mat = np.array([[4, 8, 1], [5, 10, 6]])

print(np.argmax(mat)) # prints 4
print(np.argmax(mat, axis=1)) # prints [1 1], index of maximum values along the rows

Does Kotlin have a similar (built in) function? I found a Kotlin bindings for NumPy, but I didn't find the function implemented.

Thanks in advance!

like image 865
dzsezusz Avatar asked Sep 16 '25 01:09

dzsezusz


1 Answers

Use withIndex() and maxByOrNull():

fun <T : Comparable<T>> Iterable<T>.argmax(): Int? {
    return withIndex().maxByOrNull { it.value }?.index
}
like image 160
Marcin Mrugas Avatar answered Sep 18 '25 18:09

Marcin Mrugas