Search code examples
phprecursiongenerator

How do you generate a list of all possible strings given a generator of characters and a length?


For example given ['a', 'b'] (as a generator) and 2 as a length

the function would output a generator that would yield:

'',
'a',
'b',
'ab'
'ba'
'aa'
'bb'

or given ['a'] and a length of 3:

'',
'a',
'aa',
'aaa',

As you could imagine this set would get a lot larger if more letters were added or length was increased, it should list all permutations of the given characters up until the length


Solution

  • Here's a fairly self-explanatory solution.

    //Returns all permuations of a certain length.
    function perm($ls, $len) {
        if($len <= 0) {
            yield '';
        }
        else {
            foreach ($ls as $x) {
                foreach(perm($ls, $len-1) as $i) {
                   yield $x.$i;
                }
            }
        }
    }
    
    //Returns all permuations of all lengths less or equal to the given integer.
    function all_perm($ls, $len) {
        //$ls = iterator_to_array($ls);
        for($x=$len; $x>=0; $x--) {
            foreach(perm($ls, $len-$x) as $string) {
                yield $string;
            }
        }
    }
    

    Simply call all_perm with your array and maximum length. If the argument absolutely have to be a generator, uncomment $ls = iterator_to_array($ls);.