malloy
July 14, 2021, 1:13pm
#1
Here’s my code;
function rot13(str) {
const input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const output = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm';
let encoded = '';
for (let i=0; i < str.length; i++) {
const index = input.indexOf(str[i]);
encoded += output[index];
}
return encoded;
}
console.log(rot13(“SERR PBQR PNZC”));
The issue with your code is that you are assuming every character in str
can be found in output
. You only want to encode letters, so what do you want to do when a character in str
is not a letter? You need to take this into account in the for
loop.
malloy
July 15, 2021, 12:31pm
#3
Here’s what I did on the for
loop, Thanks for pointing it out. It works now.
for(let i=0; i < str.length; i++){
if(str.charCodeAt(i)>=65 && str.charCodeAt(i)<=77){
arr.push(String.fromCharCode(str.charCodeAt(i)+13));
} else if(str.charCodeAt(i)>=78 && str.charCodeAt(i)<=90){
arr.push(String.fromCharCode(str.charCodeAt(i)-13));
} else if(str.charCodeAt(i)<65){
arr.push(str[i]);
}
system
closed
January 14, 2022, 12:31am
#4
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.