Saturday, August 31, 2019

Recursion Generating Sub String Given a String.

I was hitting my hard for  the past 24 hours to generate sub strings out of a string. I am not particular ly good at programming(its a gift given to only few) but the kick to think hard enough about a problem is something fulfilling and satisfying. Here is the code below to generate sub strings out of a string in the order  of the string.

public class Program
    {
        static String OPEN_BRACKET = "{";
        static String CLOSED_BRACKET = "}";
        static String EMPTY_STRING = "";
        public static void Main(string[] args)
        {
            //Your code goes here
            Console.WriteLine("Hello, world!");
            recur("Operation",0,"",0);
        }
       
        public static void recur(String s, int index, String out1,int StartPos)
{
            if (s.Length==out1.Replace("{","").Replace("}","").Length)
            {
System.Console.WriteLine(out1);
                return;
            }


        int cntr=1;
for (int j = index;j<s.Length ; j++)
{
String sub_str = OPEN_BRACKET + s.Substring(StartPos, cntr)
+ CLOSED_BRACKET;
            cntr=cntr+1;
recur(s, j + 1, out1 + sub_str,j+1);
}
}
  }
}

No comments:

Post a Comment