Sliding / Sliding Window, a Scala language concept

Last updated

Get fixed-length sliding sub-sequences (sliding windows) from another sequence

``````assert(List.empty.sliding(2).toList == List.empty)

assert(List(1).sliding(2).toList == List(List(1)))

assert(List(1, 2).sliding(2).toList == List(List(1, 2)))

assert(List(1, 2, 3).sliding(2).toList == List(List(1, 2), List(2, 3)))

assert(
List(1, 2, 3, 4).sliding(2).toList ==
List(List(1, 2), List(2, 3), List(3, 4))
)
``````

Note that if the length of the input list is less than the sliding window, then the whole input list will be returned)

For Iterators

It even works on Iterators:

``````assert(Iterator.empty.sliding(2).toList == List())

assert(Iterator(1).sliding(2).toList == List(Seq(1)))

assert(Iterator(1, 2).sliding(2).toList == List(Seq(1, 2)))

assert(Iterator(1, 2, 3).sliding(2).toList == List(Seq(1, 2), Seq(2, 3)))
``````

Scala Algorithms: The most comprehensive library of algorithms in standard pure-functional Scala

How our 100 algorithms look

1. A description/goal of the algorithm.
2. An explanation with both Scala and logical parts.
3. A proof or a derivation, where appropriate.
4. Links to Scala concepts used in this specific algorithm, also unit-tested.
5. An implementation in pure-functional immutable Scala, with efficiency in mind (for most algorithms, this is for paid subscribers only).
6. Unit tests, with a button to run them immediately in our in-browser IDE.

Study our 100 Scala Algorithms: 6 fully free, 100 published & 0 upcoming

Fully unit-tested, with explanations and relevant concepts; new algorithms published about once a week.

Explore the 22 most useful Scala concepts

To save you going through various tutorials, we cherry-picked the most useful Scala concepts in a consistent form.

Subscribe to Scala Algorithms

Maximize your Scala with disciplined and consistently unit-tested solutions to 100+ algorithms.

Use it from improving your day-to-day data structures and Scala; all the way to interviewing.