通过在JavaScript中用char数组替换一个char来生成所有可能的字符串

时间:2018-03-14 11:00:49

标签: javascript string

我有'pXoX prawa'之类的字符串,它们可能包含随机数的X.我想用抛光特殊字符替换这些X

['ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż']

并生成包含所有可能变体的字符串。在“pXoX prawa”的情况下有两个X,所以所有可能的组合是9 ^ 2 = 81,其中9是波兰特殊字符的数量。我可以用暴力程序对它进行编程,但我想知道是否有人可以提出1-2线解决方案。也许一些递归编码。任何的想法?如果你想使用外部库没问题。

2 个答案:

答案 0 :(得分:1)

使用一点递归你应该能够处理多个X的组合。

这是一个显示它的片段..



var array = ['ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż'];
var input = 'pXoX prawa';

const inputs = input.split("");

//lets store the positions of all the 'X's.
const posX = [];
inputs.forEach((i, ix) => { if(i === 'X') posX.push(ix); });

//lets have a counter for the loop
var c = 0;

function loop(idx) {
  for (let l = 0; l < array.length; l ++) {
    //lets change the letter from array.
    inputs[posX[idx]] = array[l];
    if (idx < posX.length -1) {      
      loop(idx + 1);
    } else {
      //ok all X's are filled for this itteration
      //lets log it.
      c ++;
      console.log(c, inputs.join(""));
    }
  }
}

loop(0);
&#13;
&#13;
&#13;

请注意,此代码段console.log预览在流出控制台缓冲区时不会显示所有组合。在浏览器控制台中查看全部81。

答案 1 :(得分:1)

您可以使用通用函数生成重复的所有n组合,并将每个组合应用于模板:

function* combinationsWithRepetitions(a, n) {
    if (n < 2) {
        yield* a;
        return;
    }

    for (let x of a)
        for (let c of combinationsWithRepetitions(a, n - 1))
            yield [x].concat(c);
}
 
//

chars = 'ABCD'
template = 'X and X'

for (let c of combinationsWithRepetitions(chars, 2))
    console.log(template.replace(/X/g, _ => c.shift()))

请注意,由于它是作为生成器实现的,因此它可以在任意大输入上正常工作。

这很容易扩展到任意数量的占位符:

template = 'X and X and X....X'
len = template.match(/X/g).length

for (let c of combinationsWithRepetitions(chars, len))
    etc