Queen of Spades
Queen of Spades

Reputation: 13

find the first element in a list beyond some index and satisfying some condition

I have as Input:

I want to find the index of the first positive element in that list but ignoring all the indices that are strictly smaller than givenIndex

For example if givenIndex=2 and the list is listOf(1, 0, 0, 0, 6, 8, 2), the expected output is 4 (where the value is 6). The following code gives the first positive element but It doesn't take into account ignoring all the indices that are smaller than givenIndex.

val numbers = listOf(1, 0, 0, 0, 6, 8, 2)
val output = numbers.indexOfFirst { it > 0 } //output is 0 but expected is 4

Upvotes: 0

Views: 621

Answers (1)

val givenIndex = 2
val output = numbers.withIndex().indexOfFirst { (index, value) -> index >= givenIndex && value > 0 }

Upvotes: 1

Related Questions