Home > database >  Given an array of Long values in Kotlin and a position parameter, when the position is in the middle
Given an array of Long values in Kotlin and a position parameter, when the position is in the middle

Time:11-29

Spotify's lyrics API provides an Array of miliseconds to mark when the lyric line has changed. Having a Media Player that updates it's position every 50ms, how should i code in Kotlin the way to find the correct lyric line? The position param can be in the middle of two values of the array, so I want to get the lowest one of that two.

I tried to get the lowest value compared to the position parameter but lol, it will always be the first value of the Array... Silly fault of mine.

CodePudding user response:

If I correctly understand, you need simply use min function for compare two numbers in Kotlin and find the low one: link

CodePudding user response:

Insert the position param into the array, sort it, find its index and use it to get the closest value.


    val array: MutableList<Long> = mutableListOf(4L, 9L, 5L, 1L)
    val position = 7L
    
    array.add(position)
    println(array[array.sorted().indexOf(position) - 1])

Output: 5

  • Related