Reputation: 41
Im a beginner programmer and I know that this is probably an easy problem, Im having difficulty understanding the logic. Im working on a program that deciphers Caesars Cipher with ROT13 cipher. Its one of the tasks at FreeCodeCamp. But their solutions are quite hard for me to understand at my skill level, so I want to make it my own way. I managed to get it quite far but i stumbled upon a problem. Im working with arrays, and I will return the array with deciphered message. The output in this case should be [F, R, E, E, , C, O, D, E, , C, A, M, P], but instead I get [undefined, "R", undefined, undefined, undefined, "O", undefined, undefined, undefined, undefined, undefined, "P"]. I understand that I get undefined because j+13 is bigger than 26 in cases of undefined and there are only 26 letters in alphabet or in array. I cant figure out how to make, so that alphabet will repeat itself in the cases where j+13 > 26. Any tips would be really helpful
let str = "SERR PBQR PNZC";
let strArr = str.split("");
let alphabet = [];
let tempArr = [];
for (i = 65; i <= 90; i++){
alphabet.push(String.fromCharCode(i))
}
for (i = 0; i < strArr.length; i++) {
for (j = 0; j < alphabet.length; j++) {
if (strArr[i] === alphabet[j]) {
tempArr.push(alphabet[j+13]);
}
}
}
console.log(tempArr);
Upvotes: 2
Views: 82
Reputation: 141829
alphabet[j+13]
is often undefined since j+13
is past the end of the alphabet whenever j >= 13
. You can use the remainder operator % to effectively wrap around to the beginning of the array again instead of going past the end of it. Just change it to alphabet[(j+13)%26]
:
let str = "SERR PBQR PNZC";
let strArr = str.split("");
let alphabet = [];
let tempArr = [];
for (i = 65; i <= 90; i++){
alphabet.push(String.fromCharCode(i))
}
for (i = 0; i < strArr.length; i++) {
for (j = 0; j < alphabet.length; j++) {
if (strArr[i] === alphabet[j]) {
tempArr.push(alphabet[(j+13)%26]);
}
}
}
console.log(tempArr);
Upvotes: 1