如何在 PHP 的所有变体中分割字符串

发布于 2024-10-31 11:34:19 字数 179 浏览 4 评论 0原文

我为我的英语感到抱歉。 我需要所有变体中的除法字符串函数,顺序和长度保持不变。

输入 'abc'

输出 'abc / a,bc / ab,c / a,b,c'

输入 'rrd'

输出 'rrd / r,rd / rr,d / r,r,d'

谢谢

I am sorry for my english.
I need function for division string in all variations, order and lenght remain the same.

input 'abc'

output 'abc / a,bc / ab,c / a,b,c'

or

input 'rrd'

output 'rrd / r,rd / rr,d / r,r,d'

thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝眼睛不忧郁 2024-11-07 11:34:19

检查这个“漂亮”的代码,对我来说是很好的大脑训练器:)
它确实需要一些优化,但效果很完美。
注意: array_reverse() 和 strrev() 可以删除,但这样顺序看起来更好。

function TheFunction($s) {
    for($i=strlen($s)-1;$i>0;$i--) $h .= '1';
    $z = str_replace('1','0',$h);
    for($i=bindec($h);$i>=0;$i--) $array[] = strrev(substr_replace($z, decbin($i), strlen($z)-strlen(decbin($i))));
    foreach($array as $value){
        $value = str_replace(array('0','1'),array(' ',','),$value);
        $string = '';
        for($i=0;$i<strlen($s)-1;$i++) $string .= $s[$i].$value[$i];
        $string .= $s[strlen($s)-1];
        $results[] = str_replace(' ','',$string);
    }
    return array_reverse($results);
}

示例

print_r(TheFunction('Anne'));

返回

Array
(
    [0] => Anne
    [1] => A,nne
    [2] => An,ne
    [3] => A,n,ne
    [4] => Ann,e
    [5] => A,nn,e
    [6] => An,n,e
    [7] => A,n,n,e
)

另一个示例

print_r(TheFunction('Stack'));

返回:

Array
(
    [0] => Stack
    [1] => S,tack
    [2] => St,ack
    [3] => S,t,ack
    [4] => Sta,ck
    [5] => S,ta,ck
    [6] => St,a,ck
    [7] => S,t,a,ck
    [8] => Stac,k
    [9] => S,tac,k
    [10] => St,ac,k
    [11] => S,t,ac,k
    [12] => Sta,c,k
    [13] => S,ta,c,k
    [14] => St,a,c,k
    [15] => S,t,a,c,k
)

Check this 'beautiful' code, nice brain-trainer for me :)
It definitely needs some optimization, but works perfect.
Note: array_reverse() and strrev() can be removed, but this way the order looks better.

function TheFunction($s) {
    for($i=strlen($s)-1;$i>0;$i--) $h .= '1';
    $z = str_replace('1','0',$h);
    for($i=bindec($h);$i>=0;$i--) $array[] = strrev(substr_replace($z, decbin($i), strlen($z)-strlen(decbin($i))));
    foreach($array as $value){
        $value = str_replace(array('0','1'),array(' ',','),$value);
        $string = '';
        for($i=0;$i<strlen($s)-1;$i++) $string .= $s[$i].$value[$i];
        $string .= $s[strlen($s)-1];
        $results[] = str_replace(' ','',$string);
    }
    return array_reverse($results);
}

Example

print_r(TheFunction('Anne'));

Returns

Array
(
    [0] => Anne
    [1] => A,nne
    [2] => An,ne
    [3] => A,n,ne
    [4] => Ann,e
    [5] => A,nn,e
    [6] => An,n,e
    [7] => A,n,n,e
)

Another Example

print_r(TheFunction('Stack'));

Returns:

Array
(
    [0] => Stack
    [1] => S,tack
    [2] => St,ack
    [3] => S,t,ack
    [4] => Sta,ck
    [5] => S,ta,ck
    [6] => St,a,ck
    [7] => S,t,a,ck
    [8] => Stac,k
    [9] => S,tac,k
    [10] => St,ac,k
    [11] => S,t,ac,k
    [12] => Sta,c,k
    [13] => S,ta,c,k
    [14] => St,a,c,k
    [15] => S,t,a,c,k
)
睡美人的小仙女 2024-11-07 11:34:19

我做了与 Anne 类似的事情,只是我使用了 Adrian Akison 的 Variations 类 这里

正如 Anne 的解决方案一样,我找到了 1 和 0 的所有变体 (Variations.cs),长度 1 小于原始字符串。 这是为了抵消逗号的.请注意,稍后我会将 1 替换为逗号,将 0 替换为空格。

“位”字符串 111 =“,,,”或 101 =“,,”等

因此,使用某些字符获取特定大小的所有变体,在本例中为 1 和 0:

    private HashSet<string> fetchBinaryVariations(int size)
    {
        HashSet<string> returnVal = new HashSet<string>();
        String variationResultItem = string.Empty;
        string[] oneZero = { "1", "0" };

        /* Generate all variations of 1's and 0's given size using Adrian Akison's handy dandy variations class */
        Variations<string> variationsList = new Variations<string>(oneZero.ToList<string>(), size, GenerateOption.WithRepetition);
        Console.WriteLine("Total Variations: {0}", variationsList.Count());

        foreach (List<string> variationItem in variationsList)
        {
            variationResultItem = String.Join("", variationItem);
            returnVal.Add(variationResultItem);
            // Console.WriteLine("Variation: {0}", variationResultItem);
        }
        return returnVal;
    }

接下来,我采用这些“Bit”字符串,将它们转换为逗号和空格,并将它们与我的原始序列合并。就我而言,我还有另一个步骤,使用枚举将数字解码为字母(未显示):

例如。 “Bit”字符串 = 101 = 将 ', ,' 分隔符添加到 1234 = '1,2 3,4' 的原始序列中

例如。 “Bit”字符串 = 111 = 分隔符 ',,,' 添加到原始序列 1234 = '1,2,3,4'

    private Dictionary<string, string> processDeliminatorsWithInputSequence(string sequence, HashSet<string> binaryVariations)
    {
        Dictionary<string, string> returnVal = new Dictionary<string, string>();
        string message = string.Empty, variationWithDelim = string.Empty, finalString = string.Empty;
        StringBuilder characterContainer = null;
        int satisfiedCnt = 0, unsatisfiedCnt = 0;

        foreach (string variation in binaryVariations)
        {
            variationWithDelim = variation.Replace('0', ' ').Replace('1', ','); // 0's are spaces and 1's are commas
            characterContainer = new StringBuilder();
            for (int i = 0; i < sequence.Length - 1; i++)
            {
                characterContainer.Append(sequence[i]); // Original Input
                characterContainer.Append(variationWithDelim[i]); // Append with space or comma
            }
            characterContainer.Append(sequence[sequence.Length - 1]); // Need to append last character from original input - offset again
            characterContainer.Replace(" ", ""); // Clean up empty spaces in final string

            finalString = decodeToAlphabet(characterContainer); // converat numerals to their alpha equivelant
            if (finalString != null)
                returnVal.Add(characterContainer.ToString(), finalString); // Add original encoding and decoded strings to hastable
            else
                unsatisfiedCnt++;

            satisfiedCnt = returnVal.Count();
        }

        message = String.Format("Input Sequence: {0}\r\nInput Binary Variations: {1}\r\n", sequence, binaryVariations.Count());
        message += String.Format("Valid Alphabet Sequence Variations: {0}\r\nInvalid Alphabet Sequence Variations: {1}", satisfiedCnt, unsatisfiedCnt);
        result.Messsage = message;
        Console.WriteLine(message);

        return returnVal;
    }

I did something similar to Anne except I used the Variations class from Adrian Akison here.

As in Anne's solution, I find all variations of 1's and 0's (Variations.cs), with a length 1 less than the original string. This is to account of offsetting the comma's. Note that later, I will replace the 1's as commas and the 0's as an empty space.

"Bit" String 111 = ",,," or 101 = ", ," etc

So, get all the variations of a certain size using certain characters, in this case 1 and 0:

    private HashSet<string> fetchBinaryVariations(int size)
    {
        HashSet<string> returnVal = new HashSet<string>();
        String variationResultItem = string.Empty;
        string[] oneZero = { "1", "0" };

        /* Generate all variations of 1's and 0's given size using Adrian Akison's handy dandy variations class */
        Variations<string> variationsList = new Variations<string>(oneZero.ToList<string>(), size, GenerateOption.WithRepetition);
        Console.WriteLine("Total Variations: {0}", variationsList.Count());

        foreach (List<string> variationItem in variationsList)
        {
            variationResultItem = String.Join("", variationItem);
            returnVal.Add(variationResultItem);
            // Console.WriteLine("Variation: {0}", variationResultItem);
        }
        return returnVal;
    }

Next, I take these "Bit" strings, convert them to commas and spaces and merge them with my original sequence. In my case, i have another step where I am decoding numerals to letters using an enum (not shown):

Ex. "Bit" String = 101 = deliminators of ', ,' added to original sequence of 1234 = '1,2 3,4'

Ex. "Bit" String = 111 = deliminators of ',,,' added to original sequence of 1234 = '1,2,3,4'

    private Dictionary<string, string> processDeliminatorsWithInputSequence(string sequence, HashSet<string> binaryVariations)
    {
        Dictionary<string, string> returnVal = new Dictionary<string, string>();
        string message = string.Empty, variationWithDelim = string.Empty, finalString = string.Empty;
        StringBuilder characterContainer = null;
        int satisfiedCnt = 0, unsatisfiedCnt = 0;

        foreach (string variation in binaryVariations)
        {
            variationWithDelim = variation.Replace('0', ' ').Replace('1', ','); // 0's are spaces and 1's are commas
            characterContainer = new StringBuilder();
            for (int i = 0; i < sequence.Length - 1; i++)
            {
                characterContainer.Append(sequence[i]); // Original Input
                characterContainer.Append(variationWithDelim[i]); // Append with space or comma
            }
            characterContainer.Append(sequence[sequence.Length - 1]); // Need to append last character from original input - offset again
            characterContainer.Replace(" ", ""); // Clean up empty spaces in final string

            finalString = decodeToAlphabet(characterContainer); // converat numerals to their alpha equivelant
            if (finalString != null)
                returnVal.Add(characterContainer.ToString(), finalString); // Add original encoding and decoded strings to hastable
            else
                unsatisfiedCnt++;

            satisfiedCnt = returnVal.Count();
        }

        message = String.Format("Input Sequence: {0}\r\nInput Binary Variations: {1}\r\n", sequence, binaryVariations.Count());
        message += String.Format("Valid Alphabet Sequence Variations: {0}\r\nInvalid Alphabet Sequence Variations: {1}", satisfiedCnt, unsatisfiedCnt);
        result.Messsage = message;
        Console.WriteLine(message);

        return returnVal;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文