在字符之间生成具有所有可能性的点


Generate dots between characters with all possibilities

我正在寻找一种在PHP中用点输出所有可能性的算法。 我们可以把 do 放在单词的任何地方,但现在允许重复两个点。 例如"注意"输出,如下所示:

note
n.ote
n.o.te
n.o.t.e
no.t.e
not.e
n.ot.e
....

下面的输出也是错误的:

n..ote (repeat dots right after each other)
.note (put dots at first of word)
note. (put dots at end of word)

递归方式:

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

迭代方式:

2^(Len-1)点的组合,其中 Len i 字长。为k = 0..2^(Len-1) - 1做一个循环,并在那些地方为每个k插入点,其中k的二进制表示包含1 s(k=2 =二进制010 => po.le

我最终通过 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');

例如,对于关键字"note"生成了 7 个字符串

对于关键字"Shaghayegh"生成了 511 个字符串