Javascript for Repetition(combinatorics)的缺失字符串字符的变体

时间:2013-03-23 03:08:01

标签: javascript combinatorics brute-force cartesian-product repeat

我的问题类似于尚待回答的THIS问题。

如何制作我的代码(或任何可能建议的javascript代码?)找到已知字符串长度的所有可能解决方案,其中包含重复变体中的多个缺失字符?

我正在尝试使用一串已知字符长度并从该字符串中找到缺少的字符。例如:

var missing_string = "ov!rf!ow"; //where "!" are the missing characters

我希望运行一个特定数组的脚本,例如:

var r = new Array("A","B","C","D","E","F","G","H","I","J","K",
                  "L","M","N","O","P","Q","R","S","T","U","V",
                  "W","X","Y","Z",0,1,2,3,4,5,6,7,8,9);

要通过重复这些缺少的字符找到所有可能的变体,以获得以下结果:

ovArfAow
ovBrfAow
ovCrfAow
...
ovBrfBow
ovBrfCow
...
etc //ignore the case insensitive, just to emphasize the example

当然,最终会在重复的所有变体中找到 ovErfLow

我已经能够使用1(单个)缺失字符。然而,当我用我的代码放入2个缺少的字符时,它显然为两个丢失的字符重复相同的数组字符,这对于重复是很好的,但我也需要找到没有重复但也可能需要3-4个缺少的字符可能会也可能不会重复。这是我到目前为止所做的:

var r = new Array("A","B","C","D","E","F","G","H","I","J","K",
                  "L","M","N","O","P","Q","R","S","T","U","V",
                  "W","X","Y","Z",0,1,2,3,4,5,6,7,8,9);
var missing_string = "he!!ow!r!d";
var bt_lng = missing_string.length;
var bruted="";

for (z=0; z<r.length; z++) {
for(var x=0;x<bt_lng;x++){
    for(var y=0;y<r.length;y++){
        if(missing_string.charAt(x) == "!"){
            bruted += r[z];
            break;
        }
        else if(missing_string.charAt(x) == r[y]){
            bruted += r[y];
        }
    }
}
console.log("br: " + bruted);
bruted="";
}

这只适用于一个“!”:

helloworAd
helloworBd
helloworCd
...
helloworLd

但是有两个或更多“!”,我得到:

heAAowArAd
heBBowBrBd
heCCowCrCd
...
heLLowLrLd

这对重复部分有好处,但我还需要测试每个缺失字符点中所有可能的数组M字符。

1 个答案:

答案 0 :(得分:1)

也许以下函数 in pure javascript 可能是您的解决方案。它使用Array.prototype.reduce创建给定字母c的笛卡尔积[{1}},其幂x取决于单词{{1}中感叹号的数量}。

n

在浏览器控制台中将其称为w