My program to generate combination of unique letters. Given a string "ABC" the program will out put "ABC","ACB","BAC","BCA","CAB","CBA". I struggled with this program for a long time to come up with my own solution in c# which is so effective but satisfying. recursion are pretty amazing to train the brain. The problem with recursion if you go all the way down how it works you will loose the track and you get confused actually how it works. Let's say you have a problem and if you can come up with how you can divide a problem into one sub problem and solve it that's it you don't have go down the rabbit hole of visualizing how recursion works.
public static void Permute(string s,string substr,string doNotInclude)
{
if(substr.Length==s.Length)
{
Console.WriteLine(substr);
// ++counter;
return;
}
for(int j=0;j<s.Length;j++)
{
if (doNotInclude.IndexOf(j.ToString())==-1)
{
string result=s.Substring(j,1);
Permute(s,substr+result,doNotInclude+j.ToString());
}
}
}
Permute("abcdefgh","","");
public static void Permute(string s,string substr,string doNotInclude)
{
if(substr.Length==s.Length)
{
Console.WriteLine(substr);
// ++counter;
return;
}
for(int j=0;j<s.Length;j++)
{
if (doNotInclude.IndexOf(j.ToString())==-1)
{
string result=s.Substring(j,1);
Permute(s,substr+result,doNotInclude+j.ToString());
}
}
}
Permute("abcdefgh","","");
No comments:
Post a Comment