2

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

arcanine
  • 1,933
  • 1
  • 15
  • 22
  • Maybe [this](https://stackoverflow.com/a/10223120/5897602) could help with the permutations, then its just dealing with the length. Have you tried anything yet we could see? This is an interesting problem. – Jaquarh Dec 18 '18 at 15:45
  • You could start with [this](https://stackoverflow.com/questions/19067556/php-algorithm-to-generate-all-combinations-of-a-specific-size-from-a-single-set) and change the `sampling` function to fit your need or use it in another loop for the different length – Nesku Dec 18 '18 at 15:52

1 Answers1

4

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);.

bjm
  • 98
  • 6