1

我的问题类似于尚未回答的这个问题。

如何使我的代码(或可能建议的任何 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

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

heAAowArAd
heBBowBrBd
heCCowCrCd
...
heLLowLrLd

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

4

1 回答 1

1

也许纯javascript中的以下函数对您来说是一个可能的解决方案。它用于Array.prototype.reduce创建c给定字母的笛卡尔积x,其能力n取决于单词中感叹号的数量w

function combinations(w) {
    var x = 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
        ),
        n = w.match(/\!/g).length,
        x_n = new Array(),
        r = new Array(),
        c = null;

    for (var i = n; i > 0; i--) {
        x_n.push(x);
    }

    c = x_n.reduce(function(a, b) {
        var c = [];
        a.forEach(function(a) {
            b.forEach(function(b) {
                c.push(a.concat([b]));
            });
        });
        return c;
    }, [[]]);

    for (var i = 0, j = 0; i < c.length; i++, j = 0) {
        r.push(w.replace(/\!/g, function(s, k) {
            return c[i][j++];
        }));
    }

    return r;
}

console.log(combinations("ov!rf!ow"))在浏览器控制台中这样调用它。

于 2013-03-23T04:21:09.020 回答