php中如何写出所有可能的单词?

发布于 2024-12-02 17:34:18 字数 597 浏览 3 评论 0原文

可能的重复:
生成任意长度的任意字母的所有组合

我正在尝试在 php 中写出 10 个字母(zzzzzzzzzz)的所有可能单词。我怎样才能做到这一点?它看起来像这样: https://i.sstatic.net/xC381.png

我尝试了一些方法,但他们只是随机生成 10 个字母,而不是从 1 个字母开始增加。顺便说一句,执行时间和它的大小不是问题。我只需要算法,如果有人用代码展示它当然会更有帮助..

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 : https://i.sstatic.net/xC381.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..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

橘香 2024-12-09 17:34:18
function words($length, $prefix='') {
    if ($length == 0) return;
    foreach(range('a', 'z') as $letter) {
        echo $prefix . $letter, "\n";
        words($length-1, $prefix . $letter);
    }
}

用法:

words(10);

在这里尝试:http://codepad.org/zdTGLtjY(单词最多 3 个字母)

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)

一向肩并 2024-12-09 17:34:18

版本 1:

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

正如 Paul 在下面的评论中指出的,这只会发送到 zzzzzzzzyz。有点慢(如果有人关心)但正确的版本是:

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

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);
骑趴 2024-12-09 17:34:18
 <?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);
}

?>
 <?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);
}

?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文