Skip to content

Instantly share code, notes, and snippets.

@hastebrot
hastebrot / partition.md
Last active April 12, 2022 10:22
Algorithm: Fixed and Sliding Windows in Kotlin
  • partitionRanges.kt: partition() implements a function for fixed and sliding windows suited for lists (not sequences) using indices/ranges.

  • partitionRecursion.kt: partitionRec() and partitionTailrec() implement such functions suited for lists using recursion and tail recursion (very inefficient). The concatenation of a lot of sequences using .plus() (or .flatten()) results in a StackOverflowException.

  • partitionIterator.kt: batch() and slide() implement such functions suited for lists and sequences (similar to the prototype implementation). Small "problem" here is that source.iterator() introduces mutual state. Does not use RingBuffer or LinkedList, instead replaces the whole List.

  • partitionZipDrop.kt: A sliding window for pairs with an offset of one, can be implemented ad hoc with this simple variant which uses zip(). This however does not work with sequenceOf(...).constrainOnce():