如何为每个标记生成具有X标记和Y值的字符串的所有可能性

时间:2010-10-13 22:05:29

标签: string recursion language-agnostic

所以,我有一个模板字符串,里面有X量的标记。假设它看起来像这样:

template = "render=@layer0@-@layer1@-@layer2@-@layer3@-@layer4@"

显然,令牌采用@tokenname@的形式。在这个假设的情况下,它有五个令牌。每个令牌都有一组不同的可能值。例如:

token0Values = ['t0value1'];
token1Values = ['t1value1','t1value2'];
token2Values = ['t2value1','t2value2','t2value3'];
token3Values = ['t3value1','t3value2'];
token4Values = ['t4value1','t4value2','t4value3','t4value4'];

我的问题是,如何生成给定模板的字符串的每个可能的排列以及每个标记的可能值?

1 个答案:

答案 0 :(得分:2)

我将在sorta php / AS

中尝试一下

标记是可能值的二维数组

{     [0] =“苹果”,“香蕉”,“梨”     [1] =“胡萝卜”,“豌豆”     [2] =“土豆”,“芹菜”,“黄油”,“肉汁” }

function getPermutations(tokens){

       var perms = array();

       //exit condition : there's only one token; 
       //total permutations = values array
       //so just return it

       if (tokens.length == 1)
           return tokens[0];

       //otherwise  
       //strip 1st element of the array as your "prefix"   

       prefices= tokens.shift();

       //get the permuations of the children

       childPermutations = getPermutations(tokens);

       //loop through the possible values, or "prefices"

       foreach (prefices as prefix){

            //concatenate to each of the child permutations

            foreach(childPermutations as perm)
                perms[]=prefix + perm;
       }

       //return the glob
       return perms;
}

可能有用,或类似的东西