freeCodeCamp Algorithm Challenge Guide: Caesars Cipher

freeCodeCamp Algorithm Challenge Guide: Caesars Cipher
0

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


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


#72

Another solution :slight_smile:

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. :grin:


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


#77

your earlier one worked as well - I tried it on my scratch pad.

One thing I can say is, you don’t need to check for individual characters like ?!,. - just check if it is in A-Z range. everything else should remain as it is.


#78

My solution uses regex to select all non alphabetical characters, and then use the spread operator to unpack the array over String.fromCharCode()

 function rot13(str) { 
        let regex = /\W/g;
        let deciphered = str.split('').map(val => {
            let currChar = val.charCodeAt();
            if (regex.test(val)) {
                return currChar;
            } else if (currChar <= 77) {
                return currChar + 13;
            } else if (currChar >= 78) {
                return currChar - 13;
            }          
        
        });

        return String.fromCharCode(...deciphered); 
    }

closed #79