views:

63

answers:

3

Say I have a list of values, this list can be of any length:

"100","200","300","400","500", ...

And I have a template string that has a few tokens that need to be replaced:

"@token1@-@token2@-@[email protected]@tokenN@"

Using the list of values, how can I generate every possible combination of the values in the template?

Values can be used more than once, so a result could be "100-100-100". Extra points for a method that takes into account an variable amount of tokens!

+2  A: 

edit: removed fixed number of tokens version

exploit recursion, just for fun:

r($values,false,$numtokens); // false to get 100-100-100 as well.

function r($values,$unique=true,$depth=3,$collect=array())
{
    if ( $depth == 0 )
    {
            print implode("-",$collect)."\n";
    } else {
            foreach ( $values as $id=>$t )
            {
                    if ( $unique ) unset($values[$id]);
                    r($values,$unique,$depth-1,array_merge($collect,array($t)));
                    if ( $unique ) $values[$id] = $t;
            }
    }
}

(this may need some adaption for different languages)

mvds
Does this assume the template string with the tokens in it is always formatted with hyphens?
Matt W
it basically gives you an array of elements, which you may use for whatever purpose. `implode("-",$collect)` means just concatenate them with `-` between elements. But you may do anything at that point of course - `$template = "..@token0@.."; foreach($collect as $id=>$el) $template=str_replace("@token$id@",$el,$template);` for example (note: first element id 0!)
mvds
+1  A: 

Python:

from itertools import permutations
list_of_values = ["100","200","300","400","500"]
template = "%s-%s-%s"
for p in permutations(list_of_values,3):
  print(template % p)

You can do combinations instead of permutations if you don't want "500-400-300" and "300-400-500" as an example.

Kevin Stock
A: 

Assuming values can be repeated:

#!/usr/bin/env python

VALUES=['100','200','300','400','500']

TOKEN='@token%d@'

TARGET="@token1@-@token2@-@token3@"

def rep(n,target):
    src=TOKEN%n
    if src not in target:
        return [target]

    ret = []
    for v in VALUES:
        ret += rep(n+1, target.replace(src,v))
    return ret

print rep(1,TARGET)
Douglas Leeder