仅存储特定字符时存储字符串的所有可能组合

Storing all possible combinations of a string when only specific characters

我正在尝试用打字稿中看起来风格相似的数字替换字母表中的字母。即字母 I 到 1。我有一个名为 replaceLettersWithNumber 的工作函数,它用所有字母完成此操作,但是,我正在努力掌握并实现一个工作解决方案,它从 Hello -> H3llo -> Hell0 延伸到最后, H3ll0.

首先调用名为howManyNumberLookingCharacters的函数,返回的数组是底层函数中的参数。我是 Whosebug 的新手,所以如果我可以提供更多信息,请告诉我。我觉得这很简单,但是我的大脑不合作!谢谢

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;
}

生成组合的最简单方法是使用递归。

在每个可用替换的级别,您都可以使用两个版本调用该函数,如下所示:

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
}

请注意,此代码假设您正在执行单个字符替换。