Hi, I'm trying to get all possible combinations of a string array and I've been doing alot of google searches but what I'm finding isn't exactly what I need. Finding alot of samples but most of them find combinations of all the items in the array like this:
string[] words = new string[] { "1", "2", "3" }
123
132
231
213
ect....
What I need is
1
2
3
12
13
21
23
31
32
123
132
213
231
312
321
ect....
Here is my code thats producing combinations of all 3
string[] words = new string[] { "1", "2", "3" }
123
132
231
213
ect....
What I need is
1
2
3
12
13
21
23
31
32
123
132
213
231
312
321
ect....
Here is my code thats producing combinations of all 3
private static List<List<string>> allCombinations = new List<List<string>>();
static void Main(string[] args)
{
string[] words = new string[] { "string1", "string2", "string3" };
string logPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"logfile.txt");
List<string> temp = new List<string>();
string temp2 = string.Empty;
StreamWriter sw = new StreamWriter(logPath);
GetCombinations(words, temp);
int i = 0; int f = 0; string str = string.Empty;
while (i < allCombinations.Count)
{
str = string.Empty; f =0;
while(f < allCombinations[i].Count)
{
str += allCombinations[i][f];
f++;
}
Console.WriteLine(str);
i++;
}
sw.Close();
}
private static void GetCombinations(string[] words, List<string> temp)
{
if (temp.Count == words.Length)
{
List<string> clone = temp.ToList();
if (clone.Distinct().Count() == clone.Count)
{
allCombinations.Add(clone);
}
return;
}
for (int i = 0; i < words.Length; i++)
{
temp.Add(words[i]);
GetCombinations(words, temp);
temp.RemoveAt(temp.Count - 1);
}
}