Scala algorithm: Make a queue using Maps
Make a pure-functional queue using Scala's
Map. It would have the following methods:
Try to make it efficient, where possible.
Test cases in Scala
Algorithm in Scala
31 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
The basic idea here is that we can use a Map as a pointer to store items, where the key is the order of the item in the queue. Then, we need to know the range of keys that are in this Map, and the perfect data structure is Scala's range.
For the first item, the range is '0 to 0' ie only 1 item, after a second item the range is '0 to 1', and after dequeueing it, the range becomes '1 to 1'; if we tried to find the range from the Map we'd be facing an operation more expensive than O(1), and for that reason we should make the range explicit. (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.
The 'Option' type is used to describe a computation that either has a result or does not. In Scala, you can 'chain' Option processing, combine with lists and other data structures. For example, you can also turn a pattern-match into a function that return an Option, and vice-versa!
(1 to n)syntax produces a "Range" which is a representation of a sequence of numbers.
A state machine is the use of `sealed trait` to represent all the possible states (and transitions) of a 'machine' in a hierarchical form.