# freeCodeCamp Algorithm Challenge Guide: Caesars Cipher

freeCodeCamp Algorithm Challenge Guide: Caesars Cipher
0

#57

###here’s a refactored solution:

function rot13(str){
return str.split(’’).map(function© {
if (/[A-Z]/.test©) {
return String.fromCharCode((c.charCodeAt() % 26) + 65);
} else {
return c;
}
}).join(’’);
}

#58

I annotated my code notes so its hopefully easy to understand

explanations below it

``````function rot13(str) {
//Convert to array simpler to calculate no string immutability
var newArr = str.split('');

//Loop each array val apply decrypt func
for (let i =0; i<newArr.length;i++){
newArr[i]= shiftValues(newArr[i]);
}

//return answers
return newArr.join('');

//---------------------------------------
//Decrypt function
function shiftValues(val){

//Ignore spaces
if (val.match(/\W/i)) {
return val;
}

//Define shift
var shift=13;

//Convert to ASCII values
val=val.charCodeAt(0);

//Equalize to base 0 index, 'A' of 65 is 0
val=val-65;

//If val-shift is negative, add 26 so it counts backwards
if ((val-shift)>=0){
val=val-shift;
} else {
val=val-shift+26;
}

//Unequalize it now
val=val+65;

//Convert to Character
val = String.fromCharCode(val);

return val;
}
//-------------------------------------

}

rot13("SERR PBQR PNZC");
``````

brief Explanation of main program:

• Convert to an array so its easy to work with
• Loop through each value in array
• Use custom function to do decrypting of each letter
• Combine resulting array into string
• Output results

Explanation of function: (as it loops each value in array)

• Ignore any spaces using regex
• Convert to ASCII number
• Make 65 so now it index0 (A=0, B=1, C=2, D=3…Y=24, Z=25)
• Do the decryption 13 shift more on this in a bit
• Unmake 65 so no longer index0
• Convert back to char
• Send char back

### explaining complicated part:

[spoiler]

Explanation of the more on this in a bit part:

I use shift = 14 as example, since its less confusing than 13 example

• Say we have “L”. Its the 11th letter in alphabet (where “A” is 0 index)
• Now let’s say our shift is 14.
• 11-14 = -3. We have a negative number. Now what?
• What value is it supposed to be?
• Its supposed to be “X” , or 3 positions away from the end of alphabet,
• X = 26-3

So we know “L” with a shift of 14 is supposed to be “X”

• “X” has a value of 23.
• “L” has a value of 11
• The shift is 14

So how do you get from a value of 11 to 23?

• 11 - 14 + ??? = 23
• ??? is 26
• There’s 26 letters in the alphabet

In summary;

If your going to have a negative number when you do your shift add 26. Otherwise, leave it as is

There’s other solutions around this using modulo operators `%`, but I didn’t use that though [/spoiler]

#59

my solution I do not know if this is true in every case or not?

``````function rot13(str) { // LBH QVQ VG!

var st="";
for (var i=0;i<str.length;i++){

st+=String.fromCharCode(str.charCodeAt(i)<65?str.charCodeAt(i):str.charCodeAt(i)+13>90?str.charCodeAt(i)-13:str.charCodeAt(i)+13);
}
return st;
}``````

#60

abusing map()

function rot13(str) { // LBH QVQ VG!

var arr = str.split(" ");

var split = arr.map(function (x){

``````return x.split('').map(function (y){
return y.charCodeAt(x);
``````

});
});

var convert = split.map(function (x){
return x.map(function (y){
if (y < 65 || y > 90){
return String.fromCharCode(y);
}
else if (y < 78) {
return String.fromCharCode (y + 13);
}
else {
return String.fromCharCode (y - 13);
}

});
});

return convert.map(function (x){
return x.join(’’);
}).join(" ");

}

// Change the inputs below to test
rot13(“GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.”);

#61

Hi, this is my solution, with the explaination. The algo in my mind was to get string, convert to array, change values of individual letters, add 13 to them and put in between the 65 to 90 set, reject any other values, take the new formed array of character code, and convert back into string. Hope it works for you guys.

``````function rot13(str) {
var arr = []; // new array variable
var fstr = []; // another new array variable

for(var i=0; i < str.length; i++){
//put the strings char codes in new array
arr[i] = str.charCodeAt(i);

//evaluate the values in the new array based on comparison with code values between 65 and 90
if(arr[i] > 64 && arr[i] < 91){

//rotate the value
arr[i] = arr[i]+13;

//if new value is more than 90, loop it back in the alphabetical order
if(arr[i] > 90){
arr[i] = 64 + (arr[i] - 90);
}
}

//enter the new looped back array into the fstr variable based on the CharCodes
fstr += String.fromCharCode(arr[i]);

}

//returning the new Caesar Ciphered string
return fstr;

}

// Change the inputs below to test
//rot13("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
//rot13("FREE LOVE?");
rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.");``````

#62

Map is another method used for iteration instead of “for or while”

#63

thanks for this clear solution. was about to lose my hair

#64

function rot13(str) {
var n = [];
for (var i = 0; i < str.length ; i++) {
n[i] = str.charCodeAt(i);
}
for ( i = 0; i < n.length; i++) {
if(n[i] >=65 && n[i] <= 90) {
if(n[i] < 78) {
n[i] += 13;
} else {
n[i] -= 13;
}
}
}
for (i = 0; i < n.length; i++) {
n[i] = String.fromCharCode(n[i]);
}
return n.join("");

}

#65

Be careful about using bracket notation with strings, as there can be some complications with the shortcut. There’s a good conversation archived on Stack Overflow about it - in particular, how they handle edge cases differently.

I still stick with `charAt()` to be explicit, i.e.

``````return ALPHA.charAt(pos);
``````

instead of

``return ALPHA[pos];``

#66

I did it this way:

function rot13(str) { // LBH QVQ VG!

var newArr = [];

for(var i = 0;i < str.length;i++) {
newArr.push(str.charCodeAt(i));

``````if(str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 77) {
newArr[i] = 91 - (65 - (newArr[i] - 13));

}else if(str.charCodeAt(i) >= 78 && str.charCodeAt(i) <= 90) {
newArr[i] = newArr[i] - 13;
}
``````

}

return String.fromCharCode.apply(0,newArr);
}

// Change the inputs below to test
rot13(“SERR PBQR PNZC”);

#67

#68

A messy and less than ideal ROT13 decoder. A huge accomplishment for me, because I somehow knocked it out in one sitting, ~30 minutes, piecing everything together with minimal doc fumbling.

I love you with my whole heart, FreeCodeCamp. Thank you for helping me suck a little bit less each day.

``````function rot13(str) { // LBH QVQ VG!
var arr = [];
var converted = [];
arr = str.split('');
for (i = 0; i < arr.length; i++) {
temp = arr[i].charCodeAt(0);
if (temp >= 65 && temp <= 90) {
if (temp <= 77) {
temp = String.fromCharCode(temp + 13);
converted.push(temp);
} else if (temp >= 78) {
temp = String.fromCharCode(temp - 13);
converted.push(temp);
}
} else if (temp < 65 || temp > 90) {
temp = String.fromCharCode(temp);
converted.push(temp);
}
}
return converted.join('');
}``````

#69

Hey I came up with this, everything is working fine here except the exclamation or full stop and question Mark too which’s giving me value “L”, i couldn’t find that little thing that where should i add that; in this logic , thank you ,if you can help me ,

``````function rot13(str) { // LBH QVQ VG!
var caesars = "";
str = str.split('');

for(var i = 0; i < str.length; i++) {

str[i] = str[i].charCodeAt();
if(str[i] <= 77){
str[i] += 13;
str[i] = String.fromCharCode(str[i]);
}
else{
str[i] -= 13;
str[i] = String.fromCharCode(str[i]);
}

}

return str.join('').replace(/[-]/g," ");

}

// Change the inputs below to test
rot13("LBH QVQ VG!");

``````

#70

The range of the letters is 65 to 90. Try again with this new information

#71

This is my code. I don’t know if one like this one has already been posted but I took so much time trying to make it work

#72

Another solution

``````function rot13(str) { // LBH QVQ VG!
const arralpha = 'abcdefghijklmnopqrstuvwxyz'.toUpperCase();
let respt='';let res;
for(let i=0;i<str.length;i++){
res = (arralpha.indexOf(str[i]) <13)?13:-13;
respt+=((arralpha.indexOf(str[i])!='-1')?arralpha[Number(arralpha.indexOf(str[i]) )+res] : str[i]);
}
return respt;
}
rot13('SERR PBQR PNZC');``````

#73

Thanks for posting! I get your explanation better than the official solution.

#74

Thanks for sharing your solution! I know how it feels.

#75

Happy that it helped you. Happy coding

#76

Hi coders,

In Intermediate Code Solution, line 5:
`str = str.split("");`
Is it all right to turn a `str` into an `array` that way?

Looking forward to your answers, thx.