How to recursively Iterate an alphabet?

2019-04-15 02:50发布

问题:

I need to write a function which iterates through alphabet (a-z) like this:
(here is an example for a-c)

a
b
c

aa
ab
ac

ba
bb
bc

ca
cb
cc

aaa
aab
aac

... and so on. (until the word has 5 characters)

any idea how to do this? I guess I need some recursive function.

回答1:

No need for recursion!

for($char = 'a'; $char != 'aaaaaa'; $char++){
    echo $char . PHP_EOL;
}


回答2:

This is a quick recursive way to do it:

function loopchars($maxlvl,$lvlnow,$cstr){
$chars = array(); //put the chaaracters in here
for($i=0;$i<count($chars);$i++){
$uj=$cstr.$chars[$i];
if($lvlnow==$maxlvl){echo $uj.'<br />';}
else{loopchars($maxlvl,$lvlnow+1,$uj);}
}
}
for($i=1;$i<6;$i++){
loopchars($i,1,'');
}

Explained: if it did not reach the maximum level to write out, it calls itself again. And it adds every character in a loop. loopchars($n,1,''); makes $n-th level iterations therefore the loop makes every level between 1 and 5.



回答3:

Why would you need recursion for this? It could be tail recursive (which means that it could just be done iteratitively). For e.g, here is a try in Python. You had tagged PHP, so if PHP has similar libraries you can try that or implement the corresponding functions in your code.

import itertools

mystr = "abcde"

for i in range(1,len(mystr)):
    for each in itertools.combinations_with_replacement(mystr,i):
        print "".join(each)