Reputation: 13
I'm just want to find all combinations of an input string, so if i use this world: "cat" i want to get something like:
c
a
t
ca
ct
ac
at
ta
tc
cat
cta
... etc
but NOT
ccc
cca
... etc
I found a lot of similar, but those get permutations just as long as the input string, or it just knocks out some. If i have 4 char long string how do I get it to give me 1, 2 and 4 char long strings?
Upvotes: 0
Views: 1942
Reputation: 475
Actually you have here 3 phases:
Permutations
Solution:
static void Main(string[] args)
{
string word = "catt";
List<string> result = new List<string>();
int total = (int)Math.Pow(2, word.Length);
for (int i = 0; i < total; i++)
{
string tempWord = string.Empty;
// pick the letters from the word
for (int temp = i, j = 0; temp > 0; temp = temp >> 1, j++)
{
if ((temp & 1) == 1)
{
tempWord += word[j];
}
}
// generate permutations from the letters
List<string> permutations;
Permutations(tempWord, out permutations);
foreach (var prm in permutations)
result.Add(prm);
}
// remove duplicates
var resultWithoutDuplicates = result.Distinct();
foreach (var w in resultWithoutDuplicates)
Console.WriteLine(w);
Console.ReadLine();
}
static void Permutations(string str, out List<string> result)
{
result = new List<string>();
if (str.Length == 1)
{
result.Add(str);
return;
}
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
string temp = str.Remove(i, 1);
List<string> tempResult;
Permutations(temp, out tempResult);
foreach (var tempRes in tempResult)
result.Add(c + tempRes);
}
}
Instead of doing the final step (remove duplication) we can use hashset instead of list, to ensure no duplication during results adding to final data structure.
Hope it helps.
Upvotes: 1