# Thread: How to solve this (probably recursively)?

1. ## How to solve this (probably recursively)?

Say you have an array: array('a', array('b', 'c'), 'd', array('e', 'f');

How can I get all possible combinations:

abde
abdf
acde
acdf

Anyone know the solution?

Edit: I should add that it needs to work with any possible array length.

2. On PHP5?

PHP Code:
``` <?phpclass Permutations implements Iterator {    protected \$a = null;    protected \$s = null;    protected \$pos = 0;    public function __construct (\$s) {        if (is_array(\$s)) {            \$this->s = array_values(\$s);            \$this->a = range(0, count(\$s) - 1);        } else {            \$this->s = (string)\$s;            \$this->a = range(0, strlen(\$this->s) - 1);        }    }    public function key() {        return \$this->pos;    }    public function current() {        \$r = array();        foreach (\$this->a as \$k) {            \$r[] = \$this->s[\$k];        }        return is_array(\$this->s) ? \$r : implode('', \$r);    }    public function next() {        if (\$this->_next()) {            \$this->pos++;        } else {            \$this->pos = -1;        }    }    public function rewind() {        sort(\$this->a);        \$this->pos = 0;    }    public function valid() {        return \$this->pos >= 0;    }    protected function _next() {        \$n = count(\$this->a);        for (\$i = \$n - 2; \$this->a[\$i] > \$this->a[\$i + 1]; \$i--) {            if (!\$i) {                return false;            }        }        for(\$j = \$n - 1; \$this->a[\$i] > \$this->a[\$j]; \$j--);        \$q = \$this->a[\$j];        \$this->a[\$j] = \$this->a[\$i];        \$this->a[\$i] = \$q;        while (++\$i < --\$n) {            \$q = \$this->a[\$n];            \$this->a[\$n] = \$this->a[\$i];            \$this->a[\$i] = \$q;        }        return true;    }} ```
Use:
PHP Code:
``` foreach (new Permutations('qwerty') as \$k => \$v) {    echo \$v, " <br> \n";}  ```

3. Actually, PHP4. But this class doesn't do exactly what I wanted; If you look at my input, it's an array:

array('a', array('b', 'c'), 'd', array('e', 'f');

'a' and 'd' never change.
It's only array('b', 'c') and array('e', 'f') that can change.

Thanks for the help

4. Originally Posted by bartb
But this class doesn't do exactly what I wanted; If you look at my input...
That is the part for you to figure out. I do not give every answer otherwise what are you learning?

http://www.tagarga.com/blok/on/070816

5. It's not exactly permutations.

I don't want edba etc.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•