问题
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