Library contents

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

  1. Start with 1, 2, 3
  2. Do this Take windows of width two
  3. Result [1, 2] and [2, 3]
A step of one makes the two windows overlap at 2.

Syntax

Kotlin 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.

From the programval readings = listOf(2, 4, 6, 8)
First output line4.0, 6.0
Lesson.kt
fun main() {
    val readings = listOf(2, 4, 6, 8)
    println(readings.windowed(3).joinToString { it.average().toString() })
    println(readings.take(2).windowed(3).size)
}
Output
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

Advertisements

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?

Given4 → 8 → 7 → 9
Worked result3

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?

Given5 → 12
Worked result1