0

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?

2
  • @Whoever voted to close as requesting an off-site resource: wrong reason. Commented Aug 10, 2015 at 16:24
  • 2
    I'd use the awesome Combinatorics Library over at CodeProject. Your scenario falls under the Variations (i.e., without Repetition) category. I've personally used this library in many situations. Commented Aug 10, 2015 at 17:29

1 Answer 1

1

Actually you have here 3 phases:

  1. Select the letters from the input word. I do that by using counter which is promoted, then looking at it as bits representation, if bit i is '1', then I choose character i. If '0' then don't.
  2. Generate permutations based on selected letters. Here I use recursive helper function Permutations
  3. Remove duplicates from the final result. Duplicates can occure in case your original word duplicate characters. for example: "catt"

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.