Reputation: 201
Assuming we are given a list of integers R = [3,5,3,6,0,6,7]
, an threshold x
(integer) and a window size (integer) p
. For example, x=4 and p = 2.
I need to find the first index t
that verifies the the following conditions:
R[t] >= 4, R[t+1] >= 4
. Since p=2, we need to only verify for two boxes t
and t+1
. If p
was equal to 3
we will need to verify for t
, t+1
and t+2
.Here the t
I am looking for is 5
(indexing is starting from 0).
How to write this in a elegant way in Kotlin (rather than looping on the elements).
A tentative that is giving an error (x=4 and p = 2. The output should be 3 since we start indexing by 0):
val numbers = listOf(1, 2, 3, 4, 6, 8, 2)
val firstIndex = numbers.find { it >= 4 for it in it..it+2-1}
Upvotes: 7
Views: 8913
Reputation: 93581
Use windowed
to check groups of values for each index in the list. Use withIndex()
so you are iterating with the indices, which you need in your final result. Then use firstOrNull()
(which find()
is a redundant alias of). And finally, take ?.index
to get the index of the first entry that satisfies the condition, or null if none satisfy.
val x = 4
val p = 3
val list = listOf(2,5,3,6,0,6,7)
val t = list
.windowed(p)
.withIndex()
.firstOrNull { (_, sublist) -> sublist.all { it >= x } }
?.index
Upvotes: 2
Reputation: 7882
val numbers = listOf(1, 2, 3, 4, 6, 8, 2)
val p = 2
val x = 4
val t = numbers.windowed(p).indexOfFirst { window -> window.all { it >= x } } // t == 3
t
will be equal to -1
in case if no matches will be found
Upvotes: 6
Reputation: 23091
If I've understood correctly, this should work:
fun main() {
val list = listOf(3,5,3,6,0,6,7)
val p = 2
val x = 4
val t = list.withIndex().windowed(p).firstOrNull() { window ->
window.all { it.value >= x }
}?.first()?.index
println(t)
}
Output:
5
Upvotes: 1