5-Min Tutorial: Caesar Cipher in Scala

Reading Time: 3 minutes

This past quarter I was enrolled in a class CS162 at UCSB called "Programming Languages". The focus of this class was to write small programming languages using Functional Programming with Scala (and a tad bit of Prolog).

One of the biggest challenges of this class was learning to code in Scala as quickly as possible. I came to the conclusion that the quickest way to learn, specially if you have a strong programming background, is to code little snippets.

Today I want to share with you a 5-Min Tutorial in which we will code the Caesar Cipher in Scala. The main focus here is using the map function that is integrated into Strings, Seq, Lists, Maps, etc...

- The Caesar Cipher

The Caesar Cipher (or Shift Cipher) is a very simple encryption technique in which one replaces each letter in the plaintext for another letter that is a fixed number of positions down the alphabet. Julius Caesar used this in his private correspondence, and I used it to tell my high school crush that I liked her, anyways...

Caesar Shift - Source: Matt_Crypto - Wikipedia
Caesar Shift - Source: Matt_Crypto - Wikipedia

 

- Let's Code!

Scala is a nifty language that allows you to do functional programming. Functional programming is essentially a programming paradigm that treats computation as the evaluation of mathematical functions; Essentially you avoid changing-state and mutable data. This tutorial won't really go in too deep as to what this means, but it will follow functional programming standards.

So let's start coding!
We start by  adding an object that extends App. This is the equivalent of a main function in C++/Java.

object CeasarCipher extends App{
    //Essentially a main function
}

Now we add our alphabet of allowed characters. I'm using the original A-thru-Z all caps, but you can add as many characters (minuscules, numbers, symbols, etc.) as you want.

val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

Next we read in both the shift amount that we want to apply to our text and the text itself that we want to encrypt/decrypt. Notice that when we take the shift amount we are doing a bit of math. This is because I wanted to be able to shift something by +7 and then decrypt by shifting with -7. So what we are doing is simple modular math. (7 + 26) % 26 = 7; (-7 + 26) % 26 = 19.

val shift = (scala.io.StdIn.readLine("Shift By: ").toInt + alphabet.size) % alphabet.size
val inputText = scala.io.StdIn.readLine("Secret Message: ")

Finally we get to the fun part: Encrypting/Decrypting! So here is were we see some of the Scala magic. We can use the .map function on our string to map each letter of our string to the new ciphered value. What this means is that we will look at each letter, determine if it on our alphabet of allowed values, and (assuming it is) we will shift that letter by a given amount.
So let's break this down:

  1. First we find where our letter is in our alphabet. (I am only allowing upercase letters, so I have my toUpper there to avoid any lowercase to get through.)
  2. If it is not in the string we leave it be, and that single solitary c will be mapped to itself.
  3. Otherwise if it is, we shift the letter. We must be careful and mod by the alphabet.size just in case we have to wrap around to the beginning of our alphabet.
val outputText = inputText.map( (c: Char) =>; {
    //We find the c char in our allowed alphabet
    val x = alphabet.indexOf(c.toUpper)
    //If the c char is in our alphabet then we encrypt it
    //If it is not then we leave it be.
    if (x == -1){
        c
    }
    else{
        alphabet((x + shift) % alphabet.size)
    }
});

Last, but not least, don't forget to print!

println(outputText);

When we put it all together we get:

Here it is in action:

Caesar Cipher in Scala
Caesar Cipher in Scala

Hopefully you enjoyed this tutorial. Keep an eye out for more 5-Min Tutorials coming out in the future.

Recent Posts

Recent Comments

Archives

Categories