severndigital Posted May 20, 2010 Share Posted May 20, 2010 let's say I have a string like 'abdc' I would like to return every possible arrangement of that string. Like boxing a lottery number. so the result would be something like array('abcd', 'acdb', 'acbd', 'adbc', 'adcb', and so on ) Is there an easy way to do this, or will have just have use like a ton of loops to make it work? it doesn't not have to be in any special order. i just needs to return all possible configurations of the string. Thanks in advance. P Link to comment https://forums.phpfreaks.com/topic/202407-rearrange-string/ Share on other sites More sharing options...
smarble53 Posted May 20, 2010 Share Posted May 20, 2010 http://home.bolink.org/ebooks/webP/pcook/ch04_26.htm i've had to use that once, and it works pretty well. Link to comment https://forums.phpfreaks.com/topic/202407-rearrange-string/#findComment-1061258 Share on other sites More sharing options...
teamatomic Posted May 20, 2010 Share Posted May 20, 2010 Its called permutations. I got this from the net, cant remember where. I used it to make a lotto blaster and it works great. <?php $str = '1234'; 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; } ?> To use this Generator you can do something like this : <? $Array=permutations("$str",3); for($i=0 ; $i < count($Array) ; $i++) { echo "<br>$Array[$i]"; //echo "<br>$i::$Array[$i]"; } echo "<br>There were $i permutations found!"; ?> HTH Teamatomic Link to comment https://forums.phpfreaks.com/topic/202407-rearrange-string/#findComment-1061389 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.