Keeping track of various combinations of a string containing only certain characters

Currently, I am working on a project that involves replacing letters of the alphabet with numbers resembling similar styles in typescript. For example, converting the letter 'I' to '1'. I have successfully implemented a function called replaceLettersWithNumber that accomplishes this task for all letters. However, I am facing difficulties in expanding this functionality from a simple transformation like turning 'Hello' into 'H3llo' and then further modifying it to 'H3ll0'.

The initial step involves calling a function named howManyNumberLookingCharacters to determine the count of number-like characters in the input string, which is then passed as parameters to the subsequent function. As a newcomer to StackOverflow, any suggestions or additional information you require would be highly appreciated. Although the concept seems straightforward, my current mental block is hindering progress! Thank you in advance for your assistance.

const replacementLetters = ['O', 'I', 'E', 'A', 'T'];
const replacementNumbers = ['0', '1', '3', '4', '7'];

export function howManyNumberLookingCharacters(stringToBeRead: string): {alphabeticalCharacterPosition: number[], alphabeticalCharacter: string[]} {
let alphabeticalCharacterPosition: number[] = [];
let alphabeticalCharacter: string[] = [];

for (let x = 0; x < stringToBeRead.length; x++) {
    for (let i = 0; i < replacementLetters.length; i++) {
        if (stringToBeRead.toLocaleUpperCase().charAt(x) == replacementLetters[i]) {
            alphabeticalCharacterPosition.push(x);
            alphabeticalCharacter.push(replacementLetters[i])
        }
    }
}
return {alphabeticalCharacterPosition, alphabeticalCharacter};
}

export function replaceLettersWithNumber(stringToBeRead: string, alphabeticalCharacterPosition: number[], alphabeticalCharacter: string[]): string[] {

let stringArray: string[] = [];
for (let x = 0; x < alphabeticalCharacter.length; x++) {
    var indexInArray = replacementLetters.indexOf(alphabeticalCharacter[x].toString());
    stringArray[x] = stringToBeRead.slice(0, alphabeticalCharacterPosition[x]) + replacementNumbers[indexInArray] + stringToBeRead.slice(alphabeticalCharacterPosition[x] + 1);
}
return stringArray;
}

Answer №1

To efficiently generate combinations, utilizing recursion is the way to go.

When there's a replacement option available at each level, you invoke the function with both variations, as demonstrated below:

const replacementCharacters = {
  'O': '0', 
  'I': '1', 
  'E': '3', 
  'A': '4', 
  'T': '7',
};

function replacementCombinations(input: string): string[] {
  const uppercaseInput = input.toUpperCase()
  const allCombinations: string[] = []

  function replace(str: string): void{
    if(str.length >= input.length){
      allCombinations.push(str)
      return
    }

    replace(str + input[str.length])

    if(uppercaseInput[str.length] in replacementCharacters)
      replace(str + replacementCharacters[uppercaseInput[str.length]])
  }
  replace('')
  return allCombinations
}

It’s important to note that this code assumes single character replacements are being performed.

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

Converting a UUID from a string to an integer in JavaScript

Need help passing a UUID to a function that calls an endpoint to delete a blog. The UUID is in string format like "9ba354d1-2d4c-4265-aee1-54877f22312e" and I'm encountering a TypeError: Cannot create property 'message' on string '9ba35 ...

Leverage ESlint for optimal code quality in your expressjs

Is there a way to use ESlint with Express while maintaining the no-unused-vars rule? After enabling ESlint, I am encountering the following issue: https://i.stack.imgur.com/7841z.png I am interested in disabling the no-unused-vars rule exclusively for e ...

Increase or decrease the input value by clicking on a button

Having an issue where the quantity value properly increases and decreases when clicking on the + or - button, but I also want the price to increment and decrement accordingly. I need to be able to adjust the price when clicking on the increase or decrease ...

Error encountered while attempting to sort a date column in PrimeNG data table

I am currently working with a PrimeNG Data table that includes several columns. One of the columns is a date column with the format 'DD MMM YYYY, hh:mm'. I am facing an issue with sorting this column by date without altering the date format. It a ...

Is there a way to verify if a value is undefined before including it as an object field?

I'm currently working on an Angular project and I have a query regarding TypeScript. It's about correctly handling the scenario where a field should not be included in an object if its value is undefined. In my code, I am initializing an object ...

After receiving the go-ahead from JavaScript, I am planning on integrating PHP into my project. I have come across some recommendations

Looking for assistance with AJAX functionality on a website. Specifically, users should be prompted to confirm a purchase before completing it. If they confirm, the purchase goes through; if they decline, it does not. Originally considered using PHP within ...

The file is missing the required fields in the Firestore document

I've been facing a challenge while attempting to update specific fields within a firebase document. Even though the cloud function triggers and performs an upload on the document, the values of the fields I am trying to update never seem to get upload ...

"Autocomplete disable" feature malfunctioning on the final input field of all web pages

I'm dealing with a web application that has a login page. The username and password fields have the autocomplete attribute set to "off," as well as other variations like nope, new-password etc. However, it's still not working in Chrome version 62 ...

Creating a p5.js circle on top of an HTML image: A step-by-step guide

Currently, I am integrating an image into my web application using standard JavaScript and HTML. The image represents a basic map, and my objective is to utilize p5.js to draw on it. <div id="map"> <img src="Assets/MENA.jpg" ...

Struggling to generate components using JQuery

I'm currently working on a form that checks the availability of a username using jQuery. Here is the initial form code: <form> <input id="checkuser" type="text" name="user" placeholder="Your username"/> </form> Below is the jQuer ...

Tips on how to update the status variable to true depending on the index value

Once I click on the close button, the value immediately changes to "Fruit." How can I achieve this? For instance: Apple close Grapes close Pineapples close Alternatively, is there a way to set the state of "cancel" to true ...

The issue of batch-wise data clustering on Google Maps when zooming in or out

//The code snippet provided below initializes a map with specified settings and clusters markers based on the data sent in patches of 10000.// var mapDiv = document.getElementById('newmap'); map = new google.maps.Map(mapDiv, { center ...

I'm struggling to activate the eventListener on several elements with the same className or ID. Unfortunately, only the initial child is being triggered in my current code implementation

Hello fellow developers, I'm facing an issue while working on a project. I have about ten menu items with the same ID, and I want to be able to edit each one when it is clicked. Here's what I tried using JavaScript: const menuElement = d ...

Accessing data from Execution Contexts in JavaScript

var value = 10; var outer_funct = function(){ var value = 20; var inner_funct = function(){ var value = 30; console.log(value); // displays 30 console.log(window["outer_funct"]["value"]); // I want to log the value 20 her ...

The angularjs ui-sortable feature is experiencing an issue where methods cannot be called on sortable before initialization. The specific method 'refresh' was attempted to be called prematurely

I'm attempting to sort a list, where I retrieve the elements from a database but... Error: unable to call methods on sortable before initialization; tried calling method 'refresh' This is my HTML: <div class="box-body" > <d ...

The for loop is throwing an error because the variable 'i' is not defined

I recently started using eslint and I'm in the process of updating my code to comply with my eslint configuration. module.exports = { env: { browser: true, commonjs: true, node: true, es2021: true, }, extends: 'eslint:recomm ...

Node.js Error: The requested URL cannot be found

I have encountered an issue in my Node project where I am getting a 'Cannot GET/' error when trying to open localhost on port 8081. I suspect that the problem lies in correctly reading the HTML file, but I'm not entirely sure. var express = ...

OnDrop event in React is failing to trigger

In my current React + TypeScript project, I am encountering an issue with the onDrop event not working properly. Both onDragEnter and onDragOver functions are functioning as expected. Below is a snippet of the code that I am using: import * as React from ...

Tips for preserving the URL of a 404 page in AngularJS

We are currently developing an angularjs application where users can publish their profiles as resumes. For example, a valid URL for a published profile would be: www.page.com/public/johnsmith However, if the URL is something like: www.page.com/public/ ...

What could be causing the table to display empty when we are passing data to the usetable function?

Visit Codesandbox to view Table While the header appears correctly, I noticed something strange. When I console log the data props, it shows all the necessary data. However, when I try to console.log row, there doesn't seem to be any single object re ...