Kotlin windowed
windowed builds groups of consecutive elements. A step of one advances the window by one reading, so neighboring groups overlap.
A simple example
windowed
- Start with 1, 2, 3
- Do this Take windows of width two
- Result [1, 2] and [2, 3]
Syntax
readings.windowed(size = 3, step = 1)
Run this example in Kotlin
Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Detect an increase in three-reading averages
A meter produces readings in a sequence where neighboring values matter. Compare the relevant adjacent samples or windows in their original order to determine how the signal changes over time.
fun main() {
val readings = listOf(2, 4, 6, 8)
println(readings.windowed(3).joinToString { it.average().toString() })
println(readings.take(2).windowed(3).size)
}
4.0, 6.0 0
With partialWindows left at its default, a list shorter than the window yields no groups. Computing averages this way makes each small window easy to inspect.
Kotlin documentation for windowed
Compare consecutive meter samples
A class records a series of four readings. Take adjacent pairs with a one-place step. How many pairs can the report compare?
Compare two shift counts
The supervisor has an opening and a closing count. Take adjacent pairs with a one-place step. How many pairs can the report compare?