Tell us what’s happening:
Describe your issue in detail here.
For instance, the letter E should turn to R, but it turns to an S, while R should, and turns to E. This is my second time writing here, so sorry in advance if I miss any important information here.
**Your code so far**
function rot13(str) {
let finalStr = ''
let lettersArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
for(let i = 0; i < str.length; i++) {
let oldIndex = lettersArr.indexOf(str[i]) + 1
let newIndex = oldIndex + 13;
let letter = ''
if(newIndex < 24) {
letter = lettersArr[newIndex]
} else if(newIndex > 24) {
newIndex -= 27
letter = lettersArr[newIndex]
}
if(str[i] === ' ') {
finalStr += ' '
} else {
finalStr += letter
}
}
console.log(finalStr)
}
rot13("SERR PBQR PNZC");
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36
Take a closer look at the way oldIndex and newIndex is determined. Taking as an example case from the description, the indexes should be such that A should be encoded as N. Is that what happens here?
Yup, the index of A is 1 (Yes arrays are zero indexed, but I added one to the index) so adding 13 will make it the letter at the 14th index, N, and vice versa, but for some reason N turns to A, but A doesn’t turn to N
As for the first part, for some reason 27 is the number that worked for me, I tried 24, which I thought would work, alongside other numbers and none of them gave good results, 15 (the letter O) plus 13 + 1 (the one I added) = 29 - 27 = 2, which is the letter B, the correct letter, this is basically the idea for indexes above 11. As for the spaces, it was more like a test, I was gonna finish it after I finish the deciphering part. And I was still using console.log instead of return as there was no way the current code would pass the tests, when it does I usually insert the return statement.
And thanks for explaining the index part, that’s new info to me. And thanks for spending time to explain the situation to me, I really appreciate that.