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

旧时模样 提交于 2021-02-18 18:00:24

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/53836020/how-do-you-generate-a-list-of-all-possible-strings-given-a-generator-of-characte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!