Scala algorithm: Print Alphabet Diamond
Given a letter such as C, print a diamond using letters A to C, for example:
A B B C C B B A
Test cases in Scala
assert(fillingLength(forLetter = 'B', toLetter = 'B') == 1) assert(fillingLength(forLetter = 'B', toLetter = 'C') == 1) assert(diamond('A') == "A") assert(diamond('B') == " A \nB B\n A ") assert(diamond('C') == " A \n B B \nC C\n B B \n A ")
Algorithm in Scala
20 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
First thing to notice that a Diamond is symmetric vertically: we can then reduce the algorithm to taking the top half, and putting the bottom half by re-using the top through reversing and dropping the last element.
We can in fact represent a range of letters using Scala's Range concept, and from that, compute the length of the padding and the filling around the diamond. (this is © from www.scala-algorithms.com)
Scala provides a simple way to repeat a character multiple times, and String interpolation enables straight-forward concatenation like you would have in languages such as PHP.
Scala concepts & Hints
Drop, Take, dropRight, takeRight
Scala's `drop` and `take` methods typically remove or select `n` items from a collection.
(1 to n)syntax produces a "Range" which is a representation of a sequence of numbers.
.viewsyntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.