Rotating the array \([1,2,3]\) by 1 element to the right returns an array \([3,1,2]\). Example:
Rotating the array \([1,2,3]\) 3 times returns us to the original array \([1,2,3]\).
Test cases in Scala
Algorithm in Scala
8 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
The most tricky part is finding the trick - which is to join two Arrays side-by-side, and then slice that array to get a continuous slice that simulates a rotation - no mutations needed!
In Scala, we use the View concept to turn our array \([1,2,3]\) into an array \([1,2,3,1,2,3]\) with concatenation (without doing any allocations yet!), and then select the expected slice. (this is © from www.scala-algorithms.com)
For example, when \(n = 1\):
Scala concepts & Hints
Drop, Take, dropRight, takeRight
Scala's `drop` and `take` methods typically remove or select `n` items from a collection.
.viewsyntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.