I'm looping through an array and adding a number to each element but the results are much higher numbers than they should be

I'm looping through an array and adding a number to each element but the results are much higher numbers than they should be
0

#1

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?


#2

With your current code, the inner loop adds 13 to every char code collected thus far every time the outer loop inserts a new char code. So when you push a char code, your code then adds 13 to everything.

I think you need to split your loops into two separate (not nested) loops. The first one takes care of collecting the char codes from each letter. Once that’s done, you’ll do the shifting in the second loop. Here you have a bit more work to do, because the string might also include spaces. So you’ll also need to check if the current char code is the char code for a space.

Adding 13 to the char code will only work if the current char code represents a letter in the lower half of the alphabet. If you’re adding 13 to the char code for a letter in the upper half, you now have a char code for a char that’s not a letter.