Last active
November 26, 2016 23:05
-
-
Save efarioli/6c56a08d447db578c9793e4cdbeb787e to your computer and use it in GitHub Desktop.
One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift 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
//javascript | |
/*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. | |
*/ | |
function isCapLetter(num) { | |
if (num >= 65 && num <= 90) { | |
return true; | |
} | |
return false; | |
} | |
function range(num, min, max) { | |
if (num >= min && num <= max) { | |
return num; | |
} else { | |
return num - max + min - 1; | |
} | |
} | |
//102 ---> 76 | |
range(100, 65, 90); | |
//65-90 | |
function rot13(str) { // LBH QVQ VG! | |
str = str.toUpperCase(); | |
var n = 0; | |
var l = ""; | |
var str2 = ""; | |
for (x = 0; x < str.length; x++) { | |
n = str.charCodeAt(x); | |
if (isCapLetter(n)) { | |
n = range(n + 13, 65, 90); | |
} | |
l = String.fromCharCode(n); | |
str2 += l; | |
} | |
return str2; | |
} | |
// Change the inputs below to test | |
rot13("serR PBQR PNZC"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment