Last active
November 9, 2019 08:25
-
-
Save pmsosa/97a46813bf23ddb2f621 to your computer and use it in GitHub Desktop.
Scala implementation of the Caesar Cipher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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