I'm trying to generate all possible combinations of a set of strings, using each string maximum once.
- The length of the output string isn't defined (the maximum length is the number of the given strings,since you can only use them once)
- For example, the stringset
array('A','B')
would generate A,B,AB,BA. - For example, the stringset
array('ABC', 'Z')
would generate 'ABC','Z', 'ZABC' and 'ABCZ'. - A stringset can have identical entries, and the output does't need te be unique.For example, the stringset
array('A', 'A')
would generate 'A', 'A','AA','AA'; (I don't actually need duplicates, but I don't want the make things more difficult)
I know that 2 strings have 4 combinations (2=>4) and 3=>15, 4=>64, 5=>325 ...
Since I'm not a programmer, I found it at least 'challenging'. Nested loops where soon too complicated. An easier solution could be finding a pattern in the indexes of array with strings. But this gives me duplicate use of the strings...
$strings = array('T','O','RS');
$num = 0;
$stringcount = count($strings);
$variations = array(0,1,4,15,64,325,1956,13699,109600,986409);
for($i=0;$i<$variations[$stringcount];$i++){
$index = base_convert($num, 10, $stringcount);
$array_of_indexes = str_split($index);
$out='';
for($j=0;$j<count($array_of_indexes);$j++){
$out .= $strings[$array_of_indexes[$j]];
}
echo $out . '<br />';
$num++;
}
Result: T O RS OT OO ORS RST RSO RSRS OTT OTO OTRS OOT OOO OORS
Not good, many duplicates + many valid combinations are not included
I know this solution is wrong in many ways, but I don't know where to start? Any Suggestions? Thx in Advance!