Generate all possible combinations when two strings are merged while retaining the same character sequence

Given two strings A and B, generate all possible combinations when B is merged into A.
Example: A = “hey”
B: “sam”
Then the combinations are:
“heysam”, “hseaym”, “hesaym”, “sahemy” etc.

Note that the character order remains the same for both the strings while merging.

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main(string[] args)
        {
            string str1 = "sam";
            string str2 = "hey";
            Merge(str1, str2, "", 0, 0, 0);
            Merge(str2, str1, "", 0, 0, 0);
        }
        public static void Merge (string str1, string str2, string str, int pos1, int pos2, int toggle)
        {
            if (str.Length == str1.Length + str2.Length)
            {
                Console.WriteLine(str);
            }
            else
            {
                if(toggle == 0)
                {
                    for (int i = 1; i <= str1.Length; i++)//string length
                    {
                        if(pos1 + i <= str1.Length)
                        {
                            Merge(str1, str2, str + str1.Substring(pos1, i), pos1 + i, pos2, 1);
                        }
                    }
                }
                else
                {
                    for (int i = 1; i <= str2.Length; i++)//string length
                    {
                        if (pos2 + i <= str2.Length)
                        {
                            Merge(str1, str2, str + str2.Substring(pos2, i), pos1, pos2 + i, 0);
                        }
                    }
                }
            }
        }
    }
}

Output
=======
shaemy
shaeym
shamey
sheaym
sheamy
sheyam
sahmey
sahemy
saheym
samhey
hseaym
hseamy
hseyam
hsaemy
hsaeym
hsamey
hesyam
hesaym
hesamy
heysam
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s