I am trying to substitute letters of the alphabet with numbers that look similar in style in typescript. I.e The letter I to 1. I have a working function named replaceLettersWithNumber which completes this with all letters, however, I am struggling to grasp and achieve a working solution where it extends from just, Hello -> H3llo -> Hell0, to finally, H3ll0.
The Function named howManyNumberLookingCharacters is called first, and the returned arrays are parameters in the bottom function. I am new to StackOverflow so please let me know if there is any more information I can provide. I feel like this is fairly straightforward, however my brain is not co-operating! Thanks.
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;
}
CodePudding user response:
The easiest way to generate combinations is to use recursion.
At each level where a replacement is available, you call the function with both versions, like this:
const replacementNumbers = {
'O': '0',
'I': '1',
'E': '3',
'A': '4',
'T': '7',
};
function replacementCombinations(input: string): string[] {
const uppercase = input.toUpperCase()
const combinations: string[] = []
function r(str: string): void{
if(str.length >= input.length){
combinations.push(str)
return
}
r(str input[str.length])
if(uppercase[str.length] in replacementNumbers)
r(str replacementNumbers[uppercase[str.length]])
}
r('')
return combinations
}
Note that this code assumes that you're doing single character replacements.
