Antarctica
Antarctica

Reputation: 201

Find the first element in a list that verify a condition

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:

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

Answers (4)

Tenfour04
Tenfour04

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

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

Adam Millerchip
Adam Millerchip

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

tscheppe
tscheppe

Reputation: 698

find Returns the first element matching the given predicate, or null if no such element was found.

Upvotes: 5

Related Questions