While watching the latest episode of The Big Bang Theory (Season 11, Episode 20), I found myself intrigued by Dr. Wolcott's unusual encryption method. In a quirky twist, this nutty theoretical cosmologist wrote his notes backward and converted all letters to numbers. This unique challenge inspired me to test my programming skills, as I am relatively new to this domain.
After some tinkering, I managed to create a function that successfully encrypted words into numbers, enabling Sheldon to communicate with Dr. Wolcott. However, decrypting these encoded numbers back into words proved to be quite a daunting task for me.
The primary hurdle lies in converting double-digit numbers back into letters.
For instance, the function encrypt('z') correctly returns 25 (the index of the letter 'z'). However, when attempting to decrypt '25', it produces 'fc' instead of 'z'.
I admit struggling with refactoring and selecting appropriate variable names, so I apologize in advance. Nevertheless, any assistance you can provide would be immensely appreciated.
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
const alphabetArray = alphabet.split('');
const encrypt = (sentence) => {
const sentenceArray = sentence.toLowerCase().split('').reverse();
const encryption = [];
for (let i = 0; i < sentenceArray.length; i += 1) {
if (sentenceArray[i] === ' ') {
encryption.push(' ');
}
for (let j = 0; j < alphabetArray.length; j += 1) {
if (sentenceArray[i] === alphabetArray[j]) {
const letterIndex = alphabetArray.indexOf(alphabetArray[j]);
encryption.push(letterIndex);
}
}
}
return encryption.join('');
};
encrypt('Abc Def');
const decrypt = (numbers) => {
const numbersArray = numbers.split('').reverse();
const decryption = [];
for (let i = 0; i < numbersArray.length; i += 1) {
if (numbersArray[i] === ' ') {
decryption.push(' ');
}
for (let j = 0; j < alphabetArray.length; j += 1) {
if (parseInt(numbersArray[i]) === alphabetArray.indexOf(alphabetArray[j])) {
decryption.push(alphabetArray[j]);
}
}
}
return decryption.join('');
};
decrypt('543 210');