The Challenge of the Universe's Origin

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');

Answer №1

Here is a code snippet that can be used as a solution to the previous comment.

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(' ');
        }
        else {
            const letterIndex = alphabetArray.indexOf(sentenceArray[i]);
            if (letterIndex < 10)
                encryption.push('0' + letterIndex);
            else
                encryption.push(letterIndex);
        }
    }
    return encryption.join('');
};

e = encrypt('abc Def');
console.log(e);

const decrypt = (numbers) => {
    const decryption = [];
    
    const numSegments = numbers.split(' ');
    for (let i = 0; i < numSegments.length; i += 1) {
        numSegment = numSegments[i];
        for (let j = 0; j < numSegment.length; j += 2){
            alphabetPosition = parseInt(numSegment.substring(j, j+2));
            decryption.push(alphabet[alphabetPosition]);
        }
        if (i < numSegments.length - 1) {
            decryption.push(' ');
        }
    }

    return decryption.reverse().join('');
};

d = decrypt('050403 020100');
console.log(d);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing a "non-serializable value found in the state" error specifically while utilizing redux toolkit, but this issue does not occur with traditional redux implementations

While transitioning my app to utilize Redux Toolkit, I encountered an error after switching over from createStore to configureStore: A non-serializable value was found in the state at path: `varietals.red.0`. Value:, Varietal { "color": "red", "id": " ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

Placement Mismatch of Radio Button in Form.Check Component of React-Bootstrap

Recently, I've been working on implementing a payment method feature where users can choose their preferred payment option using radio buttons. However, there seems to be an issue with the alignment of the button. Below is the code snippet I have so ...

Tips for displaying a prompt in the browser window using a blob response from the server

I am facing an issue with the exportChallenges button on a kendo grid in my web application. The button is supposed to export grid data to excel by using an AngularJs factory. However, when I receive the rest service response as a Blob from the server side ...

Can you explain the distinction between using .classA versus .classB.classA when styling with CSS?

When I use .show instead of .box.show in the CSS, the even boxes do not come from the left side. This discrepancy has left me puzzled as I assumed they would have the same effect. However, it appears that in this particular code snippet, they are behaving ...

Tips on avoiding the conversion of the ✳ symbol into an emoji

My issue lies in my ✳ (Eight-Spoked Asterisk) symbol being converted to an emoji on iOS/android devices. Find more about the Eight-Spoked Asterisk Emoji here. Could someone guide me on how to prevent the normal symbol ✳ from being transformed into an ...

The Firebase storage percentChanges() method is throwing a NaN error

I want to create a Firebase storage service using an Angular client to handle user profile image uploads. This service should return two observables: uploadProgress$ and downloadUrl$. The uploadProgress$ observable will store the value from percentChanges ...

Error message: "npm start cannot locate package.json file, even though the file is present

As I attempt to execute npm start within my Node.js project directory, I am facing a challenge. Despite having the package.json file in the correct location (C:\Myfirstproject\Vinci\Projet_Web), I keep encountering an error message that read ...

Execute the function when the form is submitted and show the total of the two values

I am currently working on a straightforward custom module for Drupal 7. This module takes two numeric values and upon submission, displays the sum of these values on the same page. While I have the form set up, it is not yet complete. I am facing some dif ...

Unable to modify background color in base website

While working on my project with Next.js, I encountered an issue where creating a button to change the color only affected the base web components' color and not the background color. _app.tsx import '../styles/globals.css'; import type { Ap ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

Clicking on "li" to activate and deactivate

Currently utilizing: $('#btnEmpresarial').attr('onclick','').unbind('click'); In order to deactivate a read using javascript.. However, I now require enabling the onclick after the function has completed. Is ther ...

There was an error in Angular at core.js:6150 stating that the object is not iterable due to a

I am facing an issue in displaying the First Name of a user in an HTML file getFirstName(id: any){ this.users = this.afs.collection('users', ref => ref.where("uid", "==", id)).valueChanges(); this.users.subscribe(users => { ...

Invoke a directive's function on a page by utilizing ng-click in AngularJS

Is there a way to call a function from a directive in an HTML page like index using ng-click? Below is the code for my directive: $scope.moreText = function() { $(".showMore").append(lastPart); }; html: <a ng ...

Reorganize JSON data in JavaScript

I am in the process of creating a tree structure, and I want it to be organized in the order of name, desc, then children. However, the JSON data I have received is not in this order. Is there a way to rearrange it efficiently or perhaps optimize the code ...

Is Javascript automatically generated by asp.net?

If I were to initialize a fresh VS project and paste the subsequent sample code into a freshly created page default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebApplication1._default" %> <!DOCTYPE ...

Automatically redirect to the linked page once the video concludes

Would it be feasible for a html5 video to trigger the opening of a new page upon completion? What would be the approach to achieve this using javascript? ...

When I remove the `return false` statement in my code, my AJAX call executes successfully. However, keeping it in prevents the call from

I am using jQuery to send an AJAX POST request without refreshing the page. I have tried using the return false command to prevent the page from refreshing, but then the AJAX POST request doesn't go through. If I remove the return false command, the A ...

Can values be extracted from a JSON object that is saved in a separate JavaScript file?

In my current project, I am creating unique tables dynamically and displaying them using JavaScript after making an AJAX call. Instead of writing individual code for each table, I'm looking to establish a standard layout where I can customize the desi ...

Is there a way to logout when the select event occurs using the key?

I am trying to figure out how to log out the key value when the select event is triggered. Specifically, I want to access the key={localState.id} within the <select></select> element in my HTML. This key value is crucial for a conditional stat ...