在C#中爆炸模式 [英] Explode a pattern in C#

查看:60
本文介绍了在C#中爆炸模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在c#中爆炸模式。使用给定的输入并使用递归输出给定的结果。



How can I explode a pattern in c#. Using the given input and output the given result using recursion.

The code here is unfinished because I had second thoughts about my logic. The idea is to walk through each character and decide if it was a number, or open or close parenthesis and save that information into a string, using the number to repeat what is in the parenthesis. and alowing for iteration in the event that another statement is inside the parenthesis.

For example :
2(ab)16(cd)3(a4(bc)d)

would equate to :
ABABCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDCDABCBCBCBCDABCBCBCBCDABCBCBCBCD





我的尝试:





What I have tried:

static string ExplodeString(string holder)
        {

            bool firstRun = true;
            int c = 0;
            string holderStr = "";
            int numOpen = 0;
            int numClose = 0;
            string numBuilder = "";
            int rptNum = 0;
            string holderTmp = "";
            int numOpenBraces = 0;
            string finalStr = "";
            int numCloseBraces = 0;

            if (holder.Contains("("))
            {

                int num = 4; //buffer number of chars to process for first parenthese
                while (num >0 || numOpen > numClose)
                {
                    
                    if (char.IsNumber(holder[c]) && numOpen == 0)
                    {
                        numBuilder += holder[c];
                        int.TryParse(numBuilder, out rptNum);
                        Console.WriteLine(numBuilder);
                    }
                    else if (holder[c].Equals('('))
                    {
                        Console.WriteLine("Open found!");
                        numOpen++;
                        if (numOpen > 1)
                        {
                            holderStr += holder[c];
                        }
                    }
                    else if (holder[c].Equals(')'))
                    {
                        Console.WriteLine("Close found!");
                        numClose++;
                        if (numOpen > 1)
                        {
                            holderStr += holder[c];
                        }
                    }
                    else
                    {
                        Console.WriteLine("Building string...");
                        holderStr += holder[c];
                    }
                    c++;
                    num--;
                }
                
                finalStr = String.Concat(Enumerable.Repeat(holderStr,rptNum));
                Console.WriteLine(finalStr);
                while (finalStr.Contains('('))
                {
                    finalStr = ExplodeString(finalStr);
                }
            }
            Console.WriteLine(finalStr);
            return finalStr;
        }

推荐答案

这可能是一个更有效的解决方案,但这适用于提供的输入:

There's probably a more efficient solution, but this works with the input provided:
static string ExplodeString(string value)
{
    // Matches a repeated block which does not have a nested repeated block:
    Regex pattern = new Regex(@"(?<number>\d+)\((?<text>[^()]+)\)", RegexOptions.ExplicitCapture);
    
    while (pattern.IsMatch(value))
    {
        value = pattern.Replace(value, match =>
        {
            int number = int.Parse(match.Groups["number"].Value);
            string text = match.Groups["text"].Value;
            return string.Concat(Enumerable.Repeat(text, number));
        });
    }
    
    return value;
}

// ExplodeString("2(ab)16(cd)3(a4(bc)d)")
// => "ababcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdabcbcbcbcdabcbcbcbcdabcbcbcbcd"



如果重复的文本可以包含括号,那么它将会倒下。例如, 2(ab(c))将不会展开。从问题是否存在这种可能性尚不清楚。


Where it will fall down is if the repeated text can contain parentheses. For example, 2(ab(c)) won't be expanded. It's not clear from the question whether that's a possibility.


[更新]

我们可以帮助您修复代码,但是您需要向我们展示完成(完整的一段代码。

如果你要求5位程序员为这个问题编写代码,你最终会得到6个程序。这意味着没有一个解决方案,其中有很多,有些是递归的,有些只是循环,有些是RegEx ...

这就是你需要显示代码的原因。没有完成代码,我只能给出一些一般性的建议。

-----

[Update]
We can help you fix your code, but you need to show us a finished (complete) piece of code.
If you ask 5 programmers to write a code for this problem, you will end up with 6 programs. This mean that there is not a single solution, there is many of them, some are recursive, some just loop, some RegEx ...
That is the reason you need to show your code. Without finished code, I can only give some general advices.
-----
引用:

这里的代码未完成,因为我对我的逻辑有了第二个想法。

The code here is unfinished because I had second thoughts about my logic.



不要因此而停止。只有一种方法可以知道你的想法是否有效:试一试。

作为一个学习者,你也可以通过练习来学习什么是有效的,什么是无用的,这样你就可以从中受益错误的想法。

建议:如果问题看起来太复杂了,请尝试解决一个简化的问题。

首先尝试解决问题而不嵌套,一旦你是熟悉简化问题,添加嵌套并不是很复杂。



你的问题是RLE压缩的变化:长度编码 - 维基百科 [ ^ ]



-----

学习一种或多种分析方法, EW Djikstra自上而下的方法是一个良好的开端,它将帮助您组织您的想法。

https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design [ ^ ]

https:// en.wikipedia.org/wiki/Structured_programming [ ^ ]

https://en.wikipedia.org/wiki/Edsger_W._Dijkstra [ ^ ]

https://www.cs.utexas.edu/users/EWD/ewd03xx/EWD316.PDF [ ^ ]



-----

你的代码没有按照你期望的方式运行,你不明白为什么!

有一个几乎通用的解决方案:一步一步地在调试器上运行代码,检查变量。

调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。

调试器中没有魔法,它不知道你的是什么应该这样做,它没有发现错误,它只是通过向您展示正在发生的事情来帮助您。当代码没有达到预期的效果时,你就接近了一个错误。

要查看你的代码在做什么:只需设置断点并查看代码是否正常运行,调试器允许你执行第1行第1行并在执行时检查变量。



此解决方案的缺点:

- 这是一个DIY,你是跟踪问题并找到根源的那个,这导致了解决方案。

这个解决方案的优点:

- 它也是一个很好的学习工具,因为它告诉你现实,你可以看到哪种期望与现实相符。



次要效果

- 你会为自己找到虫子感到自豪。

- 你的学习技巧会提高。



你应该很快就会发现什么是错的。



调试器 - 维基百科,免费的百科全书 [ ^ ]

在Visual Studio中调试C#代码 - YouTube [ ^ ]

调试器只是向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。



如果您需要有关代码的帮助,请显示它完成并说明你遇到的问题。


Don't stop because of this. There is only one way to know if your idea works or not: give it a try.
As a learner, you also learn what works and what don't by practicing, so you can benefit from a wrong idea.
Advice: if the problem look too complicated for you, try to solve a simplified problem.
In first try to solve the problem without nesting, once you are familiar with the simplified problem, adding the nesting is not very complicated.

Your problem is a varying of RLE compression: Run-length encoding - Wikipedia[^]

-----
Learn one or more analyze methods, E.W. Djikstra top-Down method is a good start, it will help you to organize your ideas.
https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design[^]
https://en.wikipedia.org/wiki/Structured_programming[^]
https://en.wikipedia.org/wiki/Edsger_W._Dijkstra[^]
https://www.cs.utexas.edu/users/EWD/ewd03xx/EWD316.PDF[^]

-----
When your code do not behave the way you expect, and you don't understand why !
There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

The downside of this solution:
- It is a DIY, you are the one tracking the problem and finding its roots, which lead to the solution.
The upside of this solution:
- It is also a great learning tool because it show you reality and you can see which expectation match reality.

secondary effects
- Your will be proud of finding bugs yourself.
- Your learning skills will improve.

You should find pretty quickly what is wrong.

Debugger - Wikipedia, the free encyclopedia[^]
Debugging C# Code in Visual Studio - YouTube[^]
The debugger is here to only show you what your code is doing and your task is to compare with what it should do.

If you want help on your code, show it finished and state the problem you encounter.


这篇关于在C#中爆炸模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆