代码之家  ›  专栏  ›  技术社区  ›  Matt W

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

  •  1
  • Matt W  · 技术社区  · 14 年前

    所以,我有一个模板字符串,其中包含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 回复  |  直到 11 年前
        1
  •  2
  •   user373396    14 年前

    我将在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;
    }
    

    可能有用,或者类似的东西