Created
January 17, 2017 21:50
-
-
Save SabrinaMarkon/f9a86eea18e1c6138c33ae00317251c9 to your computer and use it in GitHub Desktop.
Sabrina Markon - Algorithms - Ceasar Cipher. We are given a ROT13 string and must decode it to find the secret message.
This file contains 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
/* | |
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. | |
HTML Character Codes: http://www.ascii.cl/htmlcodes.htm | |
*/ | |
function rot13(str) { // LBH QVQ VG! | |
var newcharstr = ''; | |
var newchar = ''; | |
for (var i = 0; i < str.length; i++) { | |
var thechar = str.charCodeAt(i); | |
// only for upper case A-Z which is character codes 64-90 inclusive: | |
if (thechar >= 64 && thechar <= 90) { | |
// A-Z is a cycle from A-to-Z-to-A-to-Z like 64-to-90-to-64-to-90... | |
if (thechar > 77) { | |
// second half of the alphabet so subtract 13 | |
newchar = String.fromCharCode(thechar - 13); | |
} else { | |
// first half of the alphabet so add 13 | |
newchar = String.fromCharCode(thechar + 13); | |
} | |
} else { | |
// if it isn't A-Z, just use the same character ie. spaces, punctuation. | |
newchar = str[i]; | |
} | |
newcharstr += newchar; | |
} | |
return newcharstr; | |
} | |
// 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