Combination of String

Notice the difference between the below two approaches, loops are faster than recursion. it means the cost of calling recursive function cannot be ignored, so try to use loops instead of recursion.

below program computes the combination of string, using loops and recursion.

        static void Main(string[] args)
        {
            string str = "abcd";
            ArrayList hash = new ArrayList();
            DateTime start = DateTime.Now;
            combination(str, str.Length, hash);
            Console.WriteLine(DateTime.Now - start);

            char[] output = new char[27];
            for (int h = 0; h < 27; h++)
                output[h] = new char();
            start = DateTime.Now;
            combination_book(str, output, str.Length, 0, 0);
            Console.WriteLine(DateTime.Now - start);
            Console.ReadLine();
        }
        private static void combination_book(string s,char[] output, int len, int recLen, int start)
        {
            for (int i = start; i < len; i++)
            {
                output[recLen] = s[i];
                output[recLen + 1] = '';
                Console.WriteLine(output);

                if (i < len - 1)
                    combination_book(s, output, len, recLen + 1, i + 1);
            }
        }
        private static void combination(string s, int len, ArrayList hash)
        {
            hash.Add(s[len - 1].ToString());
            Console.WriteLine(s[len - 1].ToString());
            for (int i = len - 2; i >= 0; i--)
            {
                ArrayList tempHash = new ArrayList();
                tempHash.Add(s[i].ToString());
                Console.WriteLine(s[i].ToString());
                foreach (string comb in hash)
                {
                    tempHash.Add(s[i].ToString() + comb);
                    Console.WriteLine(s[i].ToString() + comb);
                }

                hash.AddRange(tempHash);
            }
        }

And the output

d
c
cd
b
bd
bc
bcd
a
ad
ac
acd
ab
abd
abc
abcd
00:00:00
a
ab
abc
abcd
abd
ac
acd
ad
b
bc
bcd
bd
c
cd
d
00:00:00.0156249

but when the string become long then you might have to use recursion.

Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*