0

我有以下二维数组输入:

 var arr = [ 
        ['A', ['Sun','Moon']],
        ['B', ['Cat','Dog']],
        ['C', ['John','Peter','Zora']]
 ];

使用该输入,我希望将所有组合应用于 javascript 中的给定模式:

模式中的占位符格式如下: $( name )

以下是一些带有结果的示例模式:

 var pattern1 = "$(A) / $(A)";
 /* Expected Result
    "Sun / Sun"
    "Sun / Moon"
    "Moon / Sun"
    "Moon / Moon"
 */

 var pattern2 = "$(A)--$(B)";
/* Expected Result
    "Sun--Cat"
    "Sun--Dog"
    "Moon--Cat"
    "Moon--Dog"
*/

 var pattern3 = "$(C) + $(B)";
/* Expected Result
    "John + Cat"
    "John + Dog"
    "Peter + Cat"
    "Peter + Dog"
    "Zora + Cat"
    "Zora + Dog"    
*/

  var pattern4 = "$(A) - $(A) * ( $(B) + $(C) )";
/* Expected Result
    "Sun -  Sun * ( Cat + John )"
    "Sun -  Sun * ( Cat + Peter )"
    "Sun -  Sun * ( Cat + Zora )"
    "Sun -  Sun * ( Dog + John )"
    "Sun -  Sun * ( Dog + Peter )"
    "Sun -  Sun * ( Dog + Zora )"
    "Sun -  Moon * ( Cat + John )"
    "Sun -  Moon * ( Cat + Peter )"
    "Sun -  Moon * ( Cat + Zora )"
    "Sun -  Moon * ( Dog + John )"
    "Sun -  Moon * ( Dog + Peter )"
    "Sun -  Moon * ( Dog + Zora )"
    "Moon -  Sun * ( Cat + John )"
    "Moon -  Sun * ( Cat + Peter )"
    "Moon -  Sun * ( Cat + Zora )"
    "Moon -  Sun * ( Dog + John )"
    "Moon -  Sun * ( Dog + Peter )"
    "Moon -  Sun * ( Dog + Zora )"
    "Moon -  Moon * ( Cat + John )"
    "Moon -  Moon * ( Cat + Peter )"
    "Moon -  Moon * ( Cat + Zora )"
    "Moon -  Moon * ( Dog + John )"
    "Moon -  Moon * ( Dog + Peter )"
    "Moon -  Moon * ( Dog + Zora )"
*/

模式可以是任意组合(带有重复的占位符)和任意长度。

有人可以帮助我使用javascript中的算法吗?

谢谢你。

4

2 回答 2

2

您可以一次更换一个占位符。

示例:从数组中的模式开始:

["$(A) / $(A)"]

替换第一个占位符并为所有组合创建字符串:

["Sun / $(A)", "Moon / $(A)"]

替换每个字符串中的下一个占位符并为所有组合创建字符串:

["Sun / Sun", "Sun / Moon", "Moon / Sun", "Moon / Moon"]

重复直到没有更多的占位符。

演示:http: //jsfiddle.net/Guffa/qGBpg/

于 2012-06-25T13:58:23.000 回答
0

您可以使用递归函数来执行此操作。

首先,您必须从字符串中提取名称。您可以使用正则表达式执行此操作:

var regex = /\$\(([A-Z])\)/g,
    names = [], match;

while(match = regex.exec(pattern)) {
    names.push(match[1]);
}

然后你把这个列表加上你的值的映射传递给一个递归地遍历名称的函数:

function create_combinations(pattern, names, map, index) {
    index = index || 0;
    var name = names[index],
        values = map[name],
        needle = "$(" + name + ")",
        combinations = [],
        sub;

    if (index === names.length - 1) {
        for (var i = 0, l = values.length; i < l; i++) {
            combinations.push(pattern.replace(needle, values[i]));
        }
    }
    else {
        for (var i = 0, l = values.length; i < l; i++) {
            sub = pattern.replace(needle, values[i]);
            combinations = combinations.concat(create_combinations(sub, names, map, index + 1));
        }
    }
    return combinations;
}

这要求您的数据结构将是一个对象:

var map = { 
    'A': ['Sun','Moon'],
    'B': ['Cat','Dog'],
    'C': ['John','Peter','Zora']
};

然后你用

create_combinations(pattern, names, map);

演示

于 2012-06-25T14:22:48.500 回答