Skip to content

Instantly share code, notes, and snippets.

@pmsosa
Last active November 9, 2019 08:25
Show Gist options
  • Save pmsosa/97a46813bf23ddb2f621 to your computer and use it in GitHub Desktop.
Save pmsosa/97a46813bf23ddb2f621 to your computer and use it in GitHub Desktop.
Scala implementation of the Caesar Cipher
//Ceasar (Shift) Cipher
//Pedro Miguel Sosa
//www.KonukoII.com
//Tutorial & Explanation: http://konukoii.com/blog/2016/03/24/caesar-cipher-in-scala/
object CeasarCipher extends App{
//Define Alphabet
//feel free to add more elements to your 'alphabet' (eg. Nums: 123... or Symbols: !?@#...)
val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
//We will shift our plaintext by this much
//Notice: shift = (# + 26) % 26 <-- This allows us to take any number (even if it is negative, or bigger than our alphabet size)
val shift = (scala.io.StdIn.readLine("Shift By: ").toInt + alphabet.size) % alphabet.size
//What is the code we want to encrypt/decrypt
val inputText = scala.io.StdIn.readLine("Secret Message: ")
//Lets Encrypt/Decrypt the code
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)
}
});
//Print the result
println(outputText);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment