This is part of the Caesars Cipher JavaScript problem. I have converted the string into an array of numbers and now need to shift each element up or down by 13. I did a simplified version of this to make sure I was correctly looping through so right now every number in the array should be increased by 13. Instead this is resulting in each number being much higher than it should be.
function rot13(str) {
var strNums = [];
for (i = 0; i < str.length; i ++){
strNums.push(str.charCodeAt(i)); //this gets me the correct array of numbers
for (j = 0; j < strNums.length; j++){
strNums[j] += 13; //this loop is supposed to increase each element by 13
}
}
return strNums;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
At this point my array of numbers starts at
[83, 69, 82, 82, 32, 80, 66, 81, 82, 32, 80, 78, 90, 67]
and I end up with an array that reads
[265, 238, 238, 225, 162, 197, 170, 172, 160, 97, 132, 117, 116, 80]
What am I doing wrong? I can’t even figure out how the element of the second array relate to those of the first array.
UPDATE: I figured out that the loop I have is causing each element to have 13 added to it n number of times where n is the length of str. How do I have 13 added only once to each element?