freeCodeCamp Algorithm Challenge Guide: Caesars Cipher

freeCodeCamp Algorithm Challenge Guide: Caesars Cipher
0
#52

I figured out an alternative solution for the problem :

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

var newStr = [];

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

if (str.charCodeAt(i) < 65 || str.charCodeAt(i) > 90) {
  
  newStr[i] = str[i];
  
} else  {
  
  if (str.charCodeAt(i) + 13 <= 90) {

  newStr[i] = String.fromCharCode(str.charCodeAt(i) + 13);

} else {

      newStr[i] = String.fromCharCode(str.charCodeAt(i) - 13);

}

}    

}

return newStr.join(’’);
}

// Change the inputs below to test
rot13(“SERR CVMMN!”);

0 Likes

#53

It was very hard, I needed to read and study a lot! kkkkkkkkk

function rot13(str) { // LBH QVQ VG!
var newStr = [];
for(var i=0; i<str.length; i++){
if(str.charCodeAt(i)<65 || str.charCodeAt(i)>90){
newStr.push(str[i]);
} else if (str.charCodeAt(i)>77){ // 90 -13
newStr.push(String.fromCharCode(str.charCodeAt(i)-13));
} else { // 65 +13
newStr.push(String.fromCharCode(str.charCodeAt(i)+13));
}
}
return newStr.join(’’);
}

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

2 Likes

#54

Hello, my solution is as follows. I have converted into an array to be able to use map first.

function rot13(str) { // LBH QVQ VG!
      return Array.prototype.map.call(str, function(x){
        return (x.charCodeAt(0) >= 65) ? 
          (x.charCodeAt(0) < 78 ) ?
            String.fromCharCode(x.charCodeAt(0)+13) : (x.charCodeAt(0) <= 90 ) ?
             String.fromCharCode(x.charCodeAt(0)-13) : x : x;
      }).join('');
      
    }

    // Change the inputs below to test
    rot13("SERR PBQR PNZC");
0 Likes

#55

I am not proud of my solution at all, but it works

function rot13(str) {
  let temp = '';
  for(let i = 0; i < str.length; i++) {
    let charCodeLetter = str[i].charCodeAt();
    if(charCodeLetter < 65 || charCodeLetter > 90) {
      let encodedLetter = String.fromCharCode(charCodeLetter);
       temp += encodedLetter;
    } else {
      if(charCodeLetter > 77) {
        charCodeLetter = charCodeLetter - 13;
      } else if (charCodeLetter < 78) {
        charCodeLetter = charCodeLetter + 13;
      }
       encodedLetter = String.fromCharCode(charCodeLetter);
       temp += encodedLetter;
    }
  }
  return temp;
}
rot13("SERR YBIR?");

another solution, this time more fancy

function rot13(str) { 
  let chars = str.split('');

  return chars.map(char => {
    char = char.charCodeAt();
    
    if(char < 78 && char > 64 ) char += 13;
    else if (char < 91 && char > 77) char -= 13;
    
    return String.fromCharCode(char);
  }).join('');
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");
0 Likes

#56

hrere is my solution .

function rot13(str) {
var str1=str.split(" “);
var t=[];
for(var i=0;i<str1.length;i++)
{
var r=”";
for(var j=0;j<str1[i].length;j++)
{
var c=0;
c=str1[i].charCodeAt(j);
if(c>64&&c<78)
c+=13;
else if(c>=78&&c<92)
c-=13;
r+=String.fromCharCode©;
}
t[i]=r;
}
return t.join(" ");
}
rot13(“GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.”);

0 Likes

#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(’’);
}

0 Likes

#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]

1 Like

#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;
}
0 Likes

#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.”);

0 Likes

#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.");
0 Likes

#62

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

1 Like

#63

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

0 Likes

#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("");

}

0 Likes

#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];
0 Likes

#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”);

0 Likes

#67

0 Likes

#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('');
}
2 Likes

#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!");

0 Likes

#70

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

1 Like

#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 :tired_face:

2 Likes