I'm trying to find all possible 2 letter combinations of a given string. Is there a faster way to do it, than to apply a substring position by position and then calling the function again?
Below is what I'm trying:
function permute($str) {
if (strlen($str) < 2) {
return array($str);
}
$permutations = array();
$tail = substr($str, 1);
foreach (permute($tail) as $permutation) {
$length = strlen($permutation);
for ($i = 0; $i <= $length; $i++) {
$permutations[] = substr($permutation, 0, $i) . $str[0] . substr($permutation, $i);
}
}
return $permutations;
}
$str = "tone";
$permutations = array_unique(permute($str));
$str1 = substr_replace($str, "", 1,2);
$permutations = array_unique(permute($str1));
Given the string "tone" above, I'd like to get the answers back:
to
tn
te
on
oe
ne
ot
nt
et
no
eo
en