Scala algorithm: Compute missing ranges
Published
Algorithm goal
Given a set of numbers within a range, and the specified range, find the gaps that need to be filled.
Test cases in Scala
assert(missingRanges(items = Nil, range = 0 until 0).isEmpty)
assert(missingRanges(items = List(0), range = 0 until 0).isEmpty)
assert(missingRanges(items = List(0), range = 0 to 0).isEmpty)
assert(missingRanges(items = Nil, range = 0 to 0).isEmpty)
assert(missingRanges(items = List(0), range = 0 to 1) == List(1 to 1))
assert(missingRanges(items = List(0, 1), range = 0 to 2) == List(2 to 2))
assert(missingRanges(items = List(0, 1, 5), range = 0 to 5) == List(2 to 4))
assert(
missingRanges(items = List(0, 7, 9, 19, 30), range = 0 to 50) ==
List(1 to 6, 8 to 8, 10 to 18, 20 to 29, 31 to 50)
)
Algorithm in Scala
11 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
Explanation
We use LazyLists to be able to handle possibly a larger number of items for a potentially large range.
Then, to discover the ranges that are missing, we use a Sliding / Sliding Window to find candidates and then filter them out. (this is © from www.scala-algorithms.com)
Scala concepts & Hints
Drop, Take, dropRight, takeRight
Scala's `drop` and `take` methods typically remove or select `n` items from a collection.
For-comprehension
The for-comprehension is highly important syntatic enhancement in functional programming languages.
Lazy List
The 'LazyList' type (previously known as 'Stream' in Scala) is used to describe a potentially infinite list that evaluates only when necessary ('lazily').
Range
The
(1 to n)
syntax produces a "Range" which is a representation of a sequence of numbers.Sliding / Sliding Window
Get fixed-length sliding sub-sequences (sliding windows) from another sequence