DavidW
DavidW

Reputation: 5129

function for creating combinations of strings

I'll do my best to describe what I'm trying to accomplish:

Lets say for every letter I have one or more replacements:

a = a
b = X, Z
c = c
d = W, V, M
e = e

If I'm given a string, say 'abcd', I want to create strings with combinatons of replacements, so for example 'abcd' would produce following combinations:

aXcW
aXcV
aXcM
aZcW
aZcV
aZcM

Can you help me write a function that will create and spit out an array of all the combinations regardless of how many replacements are per letter and how many occurances of replacements are in a string? So it should work with ab and abbbdddd.

Thanks

Upvotes: 2

Views: 197

Answers (1)

user187291
user187291

Reputation: 53940

here's a simple recursive solution for you

function repl($str, $map) {
    if(strlen($str) == 0)
        return array('');
    $out = array();
    foreach(repl(substr($str, 1), $map) as $r)
        foreach($map[$str[0]] as $sub)
            $out[] = $sub . $r;
    return $out;
}

use like this

$map = array(
    'a' => array('1', '2', '3'),
    'b' => array('@', '*'),
    'c' => array('X', 'Y', 'Z')
);

$result = repl("abc", $map);

To work for utf8 strings (or arbitrary substrings), the function should accept array of strings:

function repl($chars, $map) {
    if(count($chars) == 0)
        return array('');
    $out = array();
    foreach(repl(array_slice($chars, 1), $map) as $r)
        foreach($map[$chars[0]] as $sub)
            $out[] = $sub . $r;
    return $out;
}

use like this

preg_match_all('~.~u', $str, $m);
$chars = $m[0];
$result = repl($chars, $map);

Upvotes: 1

Related Questions