sammyb123
sammyb123

Reputation: 493

Loop in Caesars Cypher using JS

I have worked on this for many hours trying to solve it on my own but I came to the conclusion that I need help after several hours of hitting a dead end. I know very close but can't get rid of the spaces between words. here is my code:

function rot13(encodedStr) {
var codeArr = encodedStr.split("");
var decodedArr = []; 

var letters = ["A", "B", "C", "D", "E", "F","G", "H", "I", "J", "K", "L",      "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
var space = " ";
var location = 0;
var temp = [];
for(var i = 0; i<codeArr.length; i++){

if(letters[i] !== " "){
location = letters.indexOf(codeArr[i]);
decodedArr.push(letters[(location+13)%26]);

}else

decodedArr.push(letters[i]);
}

return decodedArr.join(""); 
}

rot13("SERR CVMMN!");

This is supposed to return "FREE PIZZA!"

Upvotes: 0

Views: 337

Answers (1)

t3dodson
t3dodson

Reputation: 4007

Some hints

Sanitation

Lets mark all letters as uppercase to avoid ambiguity between rot13('SERR CVMMN!'); and rot13('SeRR cvMmn!');

var codeArr = encodedStr.toUpperCase().split(""); // sanitize input.

Next lets handle that exclamation point

Non alpha characters should be passed through. Space is not a special case

if (/[A-Z]/.test(codeArr[i])) { // if the encoded character is an alphabet character
    // decode the character and push it on the decodedArr
} else {
    decodedArr.push(codeArr[i]); // let things like spaces and ! 
                                 // pass through to the output.
}

Encoding logic.

I think your logic is a little backwards. Instead of looping over the alphabet why not loop over the encoded text and decode sequentially?

for (var i = 0; i < codeArr.length; i += 1) {
    if (/[A-Z]/.test(codeArr[i])) { // if the encoded character is an alphabet character
        // decode the character and push it on the decodedArr
        // the decoded character is 13 ahead of the current character in base 26.
        var ACode = 'A'.charCodeAt(); // 65
        var letter = codeArr[i];
        var letterCode = letter.charCodeAt() - ACode; // ASCII code
        letterCode = (letterCode + 13) % 26;
        decodedArr.push(letters[letterCode]);
    } else {
        decodedArr.push(codeArr[i]); // let things like spaces and ! 
                                     // pass through to the output.
    }
}

Upvotes: 3

Related Questions