Caesar Cipher is just changing each letter shifting it by 13 places.
I know i can do it with indexOf
, but i tried to do it with arrays and a for..loop
but I’m having problems with it, can someone tell me what’s wrong?
function rot13(str) {
let letter = str.split("")
let cipher = [
["A", "N"],
["B", "O"],
["C", "P"],
["D", "Q"],
["E", "R"],
["F", "S"],
["G", "T"],
["H", "U"],
["I", "V"],
["J", "W"],
["K", "X"],
["L", "Y"],
["M", "Z"]
]
for (let i = 0; i < letter.length; i++) {
for (let j = 0; j < cipher.length; j++) {
if (letter[i] === cipher[j][0]) {
letter.splice(letter[i], 1, cipher[j][1])
} else if (letter[i] === cipher[j][1]) {
letter.splice(letter[i], 1, cipher[j][0])
}
}
}
return letter.join("")
}
console.log(rot13("SERR PBQR PNZC"));
2
Answers
You’ve got several issues:
letter.splice(letter[i], 1, cipher[j][1])
: In.splice()
, the first argument should be the index, not the element. Usei
instead ofletter[i]
.N-Z
toA-M
).Here’s a revised version that should work:
letter
element is an Array of 1 character,you don’t need to use
.slice()
method.just change
letter.splice(letter[i], 1, cipher[j][1])
by
letter[i] = cipher[j][1];
PS: I also added some
break;