Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How write all possible words in php? [duplicate]

Tags:

arrays

php

letter

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..

like image 366
xecute Avatar asked Sep 01 '11 12:09

xecute


2 Answers

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)

like image 71
Arnaud Le Blanc Avatar answered Oct 02 '22 03:10

Arnaud Le Blanc


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);
like image 28
Mchl Avatar answered Sep 30 '22 03:09

Mchl