I'm trying to generate all possible combinations of a string using PHP. I've searched this site for a while trying to find the right algorithm but I can't seem to find the correct one. To be more specific if i input the string "hi", I want it to return "hi", "ih", "h", "i". But I don't want it to reuse the same characters multiple times. So I wouldn't want "hh" and "ii". Is there an algorithm for this? Thanks!
Asked
Active
Viewed 677 times
-2
-
Could this solution be what you are lookin for? http://stackoverflow.com/questions/361/generate-list-of-all-possible-permutations-of-a-string#362 – kendepelchin Mar 15 '17 at 15:03
-
Have any limits? What could the max string lenght? – JustOnUnderMillions Mar 15 '17 at 15:05
-
@JustOnUnderMillions The maximum string length would probably be around 5 characters. – Njinx Mar 15 '17 at 15:06
-
@kendepelchin That answer doesn't seem to be PHP. – Njinx Mar 15 '17 at 15:09
-
3@Njinx this is not a code writing service. We can help you debug your php code once you implement logic from the answer that was linked, but actually writing code is not something that people do here. – Dimi Mar 15 '17 at 15:16
-
Like @dimi said. it should tell you enough on how to implement in the language of your choice. – kendepelchin Mar 15 '17 at 15:17
-
1Welcome to stackoverflow, please visit http://stackoverflow.com/help/how-to-ask – Olaia Mar 15 '17 at 15:29
1 Answers
1
Dont take this for production:
$string = implode('',array_unique(str_split('helpa')));
$i=0;
while($i++<50000){
$coll[substr(str_shuffle($string),0,mt_rand(1,strlen($string)))]=true;
}
ksort($coll);
print '<pre>';
print_r(array_keys($coll));
Here you can test what you want to get.
In 10000 iteration i was getting 325 combinations from a 5 length string (what seems all possible combinations)

JustOnUnderMillions
- 3,741
- 9
- 12