0

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
Robert82
  • 370
  • 2
  • 4
  • 15

1 Answers1

2

If you want to use substr

function str2array($string) {
    $strArray = [];
    for ($i = 0; $i < strlen($string); $i++) {
        $strArray[] = substr($string, $i, 1);
    }
    return $strArray;
}

But use str_split instead.

$string = 'tone';
$strArray = str_split($string);

foreach ($strArray as $key => $char1) {
    $strArray2 = $strArray;
    unset($strArray2[$key]);
    foreach ($strArray2 as $char2) {
        $permutations[] = $char1 . $char2;
    }
}
//EDIT: adding array_unique in case of dupes
$uniquePermutations=array_unique($permutations);
print_r($uniquePermutations);

Array ( [0] => to [1] => tn [2] => te [3] => ot [4] => on [5] => oe [6] => nt [7] => no [8] => ne [9] => et [10] => eo [11] => en )

chiliNUT
  • 18,989
  • 14
  • 66
  • 106