Generate dots between characters with all possibilities

后端 未结 2 1084
抹茶落季
抹茶落季 2021-01-16 11:24

I am looking for an algorithm in PHP to make output of all possibilities with dot. produces we can put do in any place of word but repeated two dots after each other is now

相关标签:
2条回答
  • 2021-01-16 11:49

    Recursive way:

    Put current char of source in the result string
    if current char is the last one
         output result
    else
         call recursive function with the next char index
         add dot to result and call recursive function with the next char index
    

    Iterative way:

    There are 2^(Len-1) combinations with dots, where Len i word length. Make a loop for k = 0..2^(Len-1) - 1 and for every k insert dots in those places, where binary representation of k contains 1s (k=2 = binary 010 = > po.le)

    0 讨论(0)
  • 2021-01-16 11:49

    I found the solution eventually by helpful guidance of https://stackoverflow.com/users/844416/mbo:

    function stringInsert($str,$insertstr,$pos){
        $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
        return $str;
    }
    
    function generate($var="note",$i=0){
        $length = strlen($var);
    
        while ($i+1 < $length) {
            $i++;
            $new = stringInsert($var,'.',$i);
            echo $new;
            generate($new,$i+1);
    
        }
    }
    
    
    generate('shaghayegh');
    

    for example for keyword "note" generated 7 strings

    for keyword "shaghayegh" generated 511 strings

    0 讨论(0)
提交回复
热议问题