Re: generate all permutations possible? (solved!)
| From: | michael geary | Date: | Fri, 04 Apr 2003 03:04:49 +0000 |
| Subject: | Re: generate all permutations possible? (solved!) | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-142239@lists.php.net to get a copy of this message | ||
beautiful! This seems to do the trick. Thanks very much!
-michael
On Thursday, April 3, 2003, at 07:45 PM, Leif K-Brooks wrote:
Try this (minimal testing, un-optimized): function permutations($letters,$num){ $last = str_repeat($letters{0},$num); $result = array(); while($last != str_repeat(lastchar($letters),$num)){$result[] = $last; $last = char_add($letters,$last,$num-1);} $result[] = $last; return $result; } function char_add($digits,$string,$char){ if($string{$char} <> lastchar($digits)){$string{$char} = $digits{strpos($digits,$string{$char})+1}; return $string;}else{$string = changeall($string,$digits{0},$char); return char_add($digits,$string,$char-1);} } function lastchar($string){ return $string{strlen($string)-1}; } function changeall($string,$char,$start = 0,$end = 0){ if($end == 0) $end = strlen($string)-1; for($i=$start;$i<=$end;$i++){$string{$i} = $char;} return $string; } michael geary wrote:Hi Folks, I'm struggling with a permutation problem. I want to take a set of characters (for example "012345678ABCDEF") and generate all permutations of length N, allowing characters to be repeated. For example, I could use this algorithm to generate all HTML hex colors by passing: generatePermutations("012345678ABCDEF",6) Granted, this example would output some 16,777,215 items, but it would be a handy thing. Note that I could get these color values by running from 0 to FFFFFF in hex, but I am looking for something more general so I can play with anagrams, etc. I have seen some algorithms that generate permutations, but I don't want all permutations of "012345678ABCDEF", I just want all 6-digit permutations. I have searched all over for algorithms, and have beat my head against it, but it is just escaping me. Can anyone help? thanks, michael-- The above message is encrypted with double rot13 encoding. Any unauthorized attempt to decrypt it will be prosecuted to the full extent of the law. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php