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  

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

  1. Drop, Take, dropRight, takeRight

    Scala's `drop` and `take` methods typically remove or select `n` items from a collection.

    assert(List(1, 2, 3).drop(2) == List(3))
    
    assert(List(1, 2, 3).take(2) == List(1, 2))
    
    assert(List(1, 2, 3).dropRight(2) == List(1))
    
    assert(List(1, 2, 3).takeRight(2) == List(2, 3))
    
    assert((1 to 5).take(2) == (1 to 2))
    
  2. Range

    The (1 to n) syntax produces a "Range" which is a representation of a sequence of numbers.

    assert((1 to 5).toString == "Range 1 to 5")
    
    assert((1 to 5).reverse.toString() == "Range 5 to 1 by -1")
    
    assert((1 to 5).toList == List(1, 2, 3, 4, 5))
    
  3. View

    The .view syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.

Algorithm in Scala

22 lines of Scala (version 2.13), showing how concise Scala can be!

This solution is available for access!

or

'Unlimited Scala Algorithms' gives you access to all the Scala Algorithms!

Upon purchase, you will be able to Register an account to access all the algorithms on multiple devices.

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  ")

View the rest of Scala algorithms