ROT13 Cipher Solution

ROT13 Cipher Solution

Programming language: JAVASCRIPT

Today is the first of 365 days of algo! We're going to go into Ciphers today. The ROT13 Caesar Cipher in particular.

Note: There are many different approaches to solve this problem, this is how I will solve the problem in an interview.

You've probably heard of a Caesar Cipher if you've done any study on cyber security, cryptography, or taken a computer science course. If you haven't, A Caesar Cipher, also known as Caesar's Cipher, shift Cipher, Caesar's code, or Caesar shift in cryptography, is one of the most basic and well-known encryption schemes. It's a substitution Cipher in which each letter in the plaintext is replaced by a letter that's a certain number of positions down the alphabet.

The most common Caesar Cipher is the ROT3. A ROT13 means each letter substituted with the 13th letter after it in the alphabet.

Training Exercise.

How can you tell an extrovert from an introvert at NSA? Va gur ryringbef, gur rkgebireg ybbxf ng gur BGURE thl'f fubrf.

I found this joke on USENET, but the punchline is scrambled. Maybe you can decipher it by creating a function that takes a string and returns the string with each letter substituted with the 13th letter after it in the alphabet (ROT13). If there are numbers or special characters included in the string, they should be returned as they are.

For example: rot13("EBG13 rknzcyr.") == "ROT13 example."; rot13("This is my first ROT13 excercise!" == "Guvf vf zl svefg EBG13 rkprepvfr!".

Solution: Let's break down the problem. Basically what we want to do is to replace our secret message(string) with the corresponding index from our Cipher and the English alphabet. we need the following 1) String of the English alphabet 2) String of ciphered alphabet 3) replaced based on indexes

      const rot13 = (str) => {
       // have a string of the alphabet
       const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 

       // have a string of the alphabet ciphered
       const cipher = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"

      // do a replace based of of indexes by using the replace()method
      return str.replace(/[a-z]/gi, letter => cipher[originalAlpha.indexOf(letter)])
}

voilà c'est ça!!! ( executes in O(1))

Conclusion

The above solution runs in constant time. The other two are quite similar, but there are many other ways to solve them.

Please post your creative solutions in the comments section below. If you have a challenge you'd like to see done, write it in the comments below and it might just get done!