My solution for Ceaser Cipher challenge doesn't work

This is my code for challenge Ceaser Cipher. It works with the letter behind “N” but doesn’t work with the letter before “N”. Pls, explain to me why my code doesn’t work. The result is “FEEE CBDE CAMC”

function rot13(str) {
    var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    str=str.split('');
    alphabet=alphabet.split('');
    for(var i=0;i<alphabet.length;i++){
        for(var j=0;j<str.length;j++){
            if(str[j]==alphabet[i] && i>=13){
                str[j]=alphabet[i-13];
            }
           else if(str[j]==alphabet[i] && i<13 )
              {str[j]=alphabet[i+13];}
           
        }
    }
    return str.join("");
}
            console.log(rot13("SERR PBQR PNZC"));

If you want good help you need to paste your actual code in here, not give us a pic. To display your code in here you need to wrap it in triple back ticks. On a line by itself type three back ticks. Then on the first line below the three back ticks paste in your code. Then below your code on a new line type three more back ticks. The back tick on my keyboard is in the upper left just above the Tab key and below the Esc key.

I have edited my question. Can you help me ?

Your logic is flipped around… Right now you are changing all As, then all Bs… etc, but what do you change the As into?

I don’t understand what you mean. My idea is that: if you see a value contained in an array Str has a value equal to a value contained in the array alphabet. You will check the index of the value in the array alphabet, if it is greater than 13, that means if you add it to 13, the result is out of the array alphabet. Because of that, you need to subtract it to 13 to guarantee the result is in the range of the array alphabet. And as you see in my code, it can turn all letters behind “N” (index=13) into the letters that have index-13. But before “N”, it doesn’t work.
Can you explain your idea clearer ?

All As becomes A+13== N, but then you later replace all Ns.

You have nested loops here.

For each letter of alphabet
You are doing fool loop through your string.

So let’s say

letter of alphabet is A and letter of string is A
in this case you’ll do a switch >>> A in string will become N. good stuff.

But lets move further through the loops.
There will be case when:

letter of alphabet is N and letter of string is N(it will be the case for N, which was switched from A earlier)
And here is the thing: your code will switch it back, from N to A.

Hint: you can solve this problem without nested loops.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.