Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
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;
        }
Posted
Updated 13-Mar-18 5:58am
v2
Comments
Patrice T 11-Mar-18 19:31pm    
What is the question?
stvn1337 11-Mar-18 19:42pm    
How can I explode said pattern imto said result using iteration in c#
Patrice T 11-Mar-18 20:38pm    
Use Improve question to update your question.
So that everyone can pay attention to this information.
BillWoodruff 11-Mar-18 20:39pm    
Did you create the format the string is in ? Is this homework ? Are you familiar with recursion, or the use of a Stack structure to implement it ?
stvn1337 11-Mar-18 20:49pm    
This is not homework, it's a real world problem I am working on as a side project for a small business. I am familiar with recursion but I am having a hard time wrapping my head around this one.

There's probably a more efficient solution, but this works with the input provided:
C#
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"

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.
 
Share this answer
 
Comments
Maciej Los 13-Mar-18 12:14pm    
I was thinking about regex too...
5ed!
Richard Deeming 13-Mar-18 12:16pm    
I was thinking that it should be possible to do something with balancing groups, but I couldn't get it to work.
Maciej Los 13-Mar-18 12:22pm    
Forget about balancing groups! :laugh: This solution is awesome!
stvn1337 13-Mar-18 12:42pm    
This solution is perfect! Thanks for giving your answer. Awesome job with the regex, I never would have thought to do it this way.
[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.
-----
Quote:
The code here is unfinished because I had second thoughts about my logic.

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.
 
Share this answer
 
v4
Comments
BillWoodruff 12-Mar-18 8:24am    
My vote of #1. This ramble has little to do with the OP's specific question.

RLE does not require recursive parsing: the OP's problem does.
Patrice T 12-Mar-18 8:41am    
With an unfinished piece of code, it is difficult to give corrections to that code, so only advices.
RLE: That is why I used the word 'varying' (may be wrong word in English, in french, I wanted to use the words 'variante' or 'variation').

I think the OP have reached the point where an analyze method will be useful and the debugger will be helpful too.
Richard MacCutchan 12-Mar-18 11:05am    
The debugger is only helpful if the questioner understands the problem in the first place. It seems that this is the only solution you ever post, whatever the question is.
Patrice T 13-Mar-18 0:28am    
It is difficult to give advices or fixes on some unfinished code, so there not much remaining.
BillWoodruff 12-Mar-18 19:44pm    
With this "logic," you might want to include your mother's recipe for chicken soup in your post.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900