Scala algorithm: Reverse a String's words efficiently
Efficiently, reverse a String's words. For example, 'Hello new world' becomes 'world new Hello'.
Test cases in Scala
Algorithm in Scala
34 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
While this may look a long-winded solution, it is very explicit and also streaming-based.
An efficiency portion of this algorithm comes from the fact that rather than appending every character that we come across to an existing string, and thus ending up with allocations of a new String per character, we can extract out the positions of the spaces, and come up with the shape of our target String by describing it in terms of the edges and where the spaces are. (this is © from www.scala-algorithms.com)
Scala concepts & Hints
'collect' allows you to use Pattern Matching, to filter and map items.
Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.
Sliding / Sliding Window
Get fixed-length sliding sub-sequences (sliding windows) from another sequence
A state machine is the use of `sealed trait` to represent all the possible states (and transitions) of a 'machine' in a hierarchical form.
.viewsyntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.