I've got a string ABC
and I'm trying to get all forms of it using recursion. For example, my goal is to make the output look like this:
A
B
C
AB
AC
BC
Currently, I'm experiencing a problem and I can't seem figure out why it's doing it. When I step through my code and get to return temp
it then goes back up to Passwords(word.Substring(start + 1, end - 1), start + 1, end);
even though the function has already completed. When it does this it removes any elements contained with my list.
class Program
{
static void Main(string[] args)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\words.txt";
string text = "abc";
List<string> passwords = Passwords(text, 0, text.Length);
foreach (string password in passwords)
{
using (StreamWriter writer = new StreamWriter(path))
{
Console.WriteLine(password);
writer.WriteLine(password);
}
}
}
public static List<string> Passwords(string word, int start, int end)
{
List<string> temp = new List<string>();
if (start == end)
{
temp.Add(word);
}
else if (word.Length == 2)
{
char[] input = word.ToCharArray();
string letter1 = input[0].ToString();
string letter2 = input[1].ToString();
string s = letter2 + letter1;
temp.Add(s);
}
else
{
if (start < end)
{
Passwords(word.Substring(start + 1, end - 1), start + 1, end);
}
}
return temp;
}
}
Can anyone help point me in the right direction as to what I'm doing wrong?