DEV Community

Mark Harless
Mark Harless

Posted on

Caesar's Cipher

Continuing on with my FreeCodeCamp algorithms and data structures! We are given this:

One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount.

A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O', and so on.

Write a function that takes a ROT13 encoded string as input and returns a decoded string.

All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.

These are my favorite types of problems. Where you can easily do it in your head but difficult when it comes down to coding it.

We can start by creating an array of the alphabet, repeated twice! Why? Because all of the letters will shift 13 characters down the alphabet. If we're given the character "z" to shift, our code would not understand that it needs to go back to "a" and continue down the alphabet. Do you want to code that? I don't. So we are just going to repeat it twice to make it easier for us.

const rot13 = str => {
  let cipher = "";
  const alphabet = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"];

  return cipher;
};
Enter fullscreen mode Exit fullscreen mode

Now we have to create a for loop where we go through each character in our str, shift it 13 spaces, then add it to our cipher. Some of the tests have punctuation, though! So we'll have to determine if our loop is seeing a character in the alphabet or something else. Here is the final result:

const rot13 = str => {
  let cipher = "";
  const alphabet = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"];

  for (let i = 0; i < str.length; i++) {
    if (/\w/.test(str[i])) {
      // checks if letter
      cipher += alphabet[alphabet.indexOf(str[i]) + 13];
    } else {
      cipher += str[i];
    }
  }

  return cipher;
};
Enter fullscreen mode Exit fullscreen mode

You can see in our for loop that we use REGEX to determine if what we're seeing is a letter or not. if it's a letter, we move it down 13 spaces then add it to our cipher variable. if it's not a letter, we simply just add it to the variable.

It's that easy! I challenge you to come up with a different way of solving this algorithm!

Top comments (2)

Collapse
 
kingleo10 profile image
Niroj Dahal • Edited

Working with ASCII value should be another solution

Collapse
 
kirankamath96 profile image
Kiran Kamath

Yes that would be pretty awesome