I am refactoring some older Java code over to Kotlin. There is a function that returns the index of the minimum value held by an element in a Kotlin IntArray within the range [a, b]. The range values default to 0 and the size of the array - 1.
I would like to do something along the lines of...
return data.minOf().indexOf()
...but while only iterating between the a and b indices of data.
Here is the function:
// data is the IntArray property that I'm looping through.
fun absMinIndex(a: Int = 0, b: Int = (data.size - 1)) : Int {
var minVal = data[a]
var minIndex = 0
for (i in (a + 1)..b) {
val e = data[i]
if (e < minVal) {
minVal = e
minIndex = i
}
}
return maxIndex
}
This [for loop] solves the issue nicely by never visiting indices out of range, and by not generating a copied array/sub-array. I'm wondering if it could be done 'prettier'.
Question
Is there a more idiomatic Kotlin approach to iterating through an array within a range that would not negatively impact the performance of my current solution?
Edited some code for clarity.