Skip to content

Instantly share code, notes, and snippets.

@MunimIftikhar
Last active November 11, 2022 10:18
Show Gist options
  • Select an option

  • Save MunimIftikhar/9ba9b8c09ee34638dab71f27ac3617b1 to your computer and use it in GitHub Desktop.

Select an option

Save MunimIftikhar/9ba9b8c09ee34638dab71f27ac3617b1 to your computer and use it in GitHub Desktop.
freeCodeCamp: Caesars Cipher

Problem Statement

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 which 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.

Input example #1

"SERR PBQR PNZC"

Expected output #1

"FREE CODE CAMP"

Input example #2

"SERR CVMMN!"

Expected output #2

"FREE PIZZA!"

Input example #3

"GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT."

Expected output #3

"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."

Input example #4

"SERR YBIR?"

Expected output #4

"FREE LOVE?"

Solution code

// Solution function
function rot13(str) {
    // alphabets will be used to identify the letter
    // position
    let alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    // key will be used to shift the letter key times
    let key = 13;
    // res will be used to store the result
    let res = "";
    // Loop through the given string
    for (let i = 0; i < str.length; i++) {
        // Check if str[i] is not a letter, if
        // true add str[i] to res and continue the loop
        if (/[^A-Z]/.test(str[i]) == true) {
            res += str[i];
            continue;
        }
        // Loop through alphabets and shift each letter
        // by key times
        for (let m = 0; m < alphabets.length; m++) {
            // Check if str[i] is equal to alphabets[m]
            if (str[i] == alphabets[m]) {
                // Check if m + key position falls under
                // the 26 letters of alphabets
                if (m + key < 26) {
                    // If true, add alphabets[m + key] to res
                    res += alphabets[m + key];
                } else {
                    // If false, move the position in circular manner
                    // by taking the mode of (m + key) with alphabets 
                    // length
                    res += alphabets[(m + key) % alphabets.length];
                }
            }
        }
    }
    // Return output array
    return res;
}

// Driver code
console.log(rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT."));

Problem link

freeCodeCamp Caesars Cipher

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment