Display possible combinations of string

前端 未结 3 1422
谎友^
谎友^ 2020-11-28 13:54

I am trying to take a string and display the possible combinations of it (in PHP), but while saying in order of each word. For example: \"how are you\" would return (an arra

3条回答
  •  无人及你
    2020-11-28 14:49

    Answer for question PHP array combination with out back order. There it was necessary to obtain all possible combinations of array elements and store the following.

     push it to result
                // find right position {
                $thisCount = count($currentElementArr);
                $indexFrom = 0;
                $indexToInsert = 0;
    
                // find range of indexes with current count of elements {
                foreach ($arrResult as $arrResultKey => $arrResultValue) {
                    $indexToInsert = $arrResultKey + 1;
                    if ($thisCount > count($arrResultValue)) {
                        $indexFrom = $indexToInsert;
                    }
                    if ($thisCount < count($arrResultValue)) {
                        --$indexToInsert;
                        break;
                    }
                }
                // find range of indexes with current count of elements }
    
                // find true index inside true range {
                $trueIndex = $indexToInsert;
                $break = false;
                for($j = $indexFrom; $j < $indexToInsert; ++$j) {
                    $trueIndex = $j + 1;
                    foreach($arrResult[$j] as $key => $value) {
                        if (array_search($value, $alphabet) > array_search($currentElementArr[$key], $alphabet)) {
                            $break = true;
                            break;
                        }
                    }
                    if($break) {
                        --$trueIndex;
                        break;
                    }
                }
                // find true index inside true range }
    
                array_splice($result, $trueIndex, 0, $currentElementStr);
                array_splice($arrResult, $trueIndex, 0, array($currentElementArr));
            }
        }
    
        for($i = 0; $i < count($shiftedAlphabet) - 1; ++$i) {
            $tmpShiftedAlphabet = $shiftedAlphabet; // for combining all possible subcombinations
            array_splice($tmpShiftedAlphabet, $i, 1);
            combine($tmpShiftedAlphabet, $result, $arrResult);
        }
    }
    // recursively create all possible combinations }
    var_dump($result); 
    
    ?>
    

    Example result here

提交回复
热议问题