开发者

How write all possible words in php? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Generate all combinations of arbitrary alphabet up to arbitrary length

I'm trying to make write all possible words of 10 letters(zzzzzzzzzz) in php. How can I do that? it will look like that : http://i.imgur.com/sgUnL.png

I tried some ways to it but they are only making 10 letters randomly not increasing from 1 letter. By the way execution time and how it's big is not problem. i just need to algorithm for it, if somebody show it with code it'll be more helpful of course.开发者_如何转开发.


function words($length, $prefix='') {
    if ($length == 0) return;
    foreach(range('a', 'z') as $letter) {
        echo $prefix . $letter, "\n";
        words($length-1, $prefix . $letter);
    }
}

Usage:

words(10);

Try it here: http://codepad.org/zdTGLtjY (with words up to 3 letters)


Version 1:

for($s = 'a'; $s <= 'zzzzzzzzzz'; print $s++.PHP_EOL);

as noted by Paul in comments below, this will only go to zzzzzzzzyz. A bit slower (if anyone cares) but correct version would be:

//modified to include arnaud576875's method of checking exit condition
for($s = 'a'; !isset($s[10]); print $s++.PHP_EOL);


 <?php

function makeWord($length, $prefix='')
{
   if ($length <= 0)
   {
      echo $prefix . "\n";
      return;
   }

   foreach(range('a', 'z') as $letter)
   {
      makeWord($length - 1, $prefix . $letter);
   }
}    

// Use the function to write the words.
$minSize = 1;
$maxSize = 3;

for ($i = $minSize; $i <= $maxSize; $i++)
{
   makeWord($i);
}

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜