Scala algorithm: Print Alphabet Diamond
Published
Algorithm goal
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!
Get the full algorithm !
or
'Unlimited Scala Algorithms' gives you access to all the 100 published Scala Algorithms!
Upon purchase, you will be able to Register an account to access all the algorithms on multiple devices.
Explanation
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.
Range
The
(1 to n)
syntax produces a "Range" which is a representation of a sequence of numbers.View
The
.view
syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.