Reputation: 163
I need to take a string of words, could be any amount of words and create an array of all possible combinations from the first word to the last word.
example input: (the input could be any amount of words, the delimiter is a space
"word1 word2 word3"
output:
1: word1
2: word1 word2
3: word1 word2 word3
4: word2
5: word2 word3
6: word3
any language is fine, but prefer c#
Upvotes: 0
Views: 698
Reputation: 24370
The haskell-solution translated to C#:
public static IEnumerable<IEnumerable<string>> Combinations(IEnumerable<string> words) {
if (words.Count() == 0) {
return new string[][] { new string[0] };
} else {
var x = words.First();
var xs = words.Skip(1);
var combinations = Combinations(xs);
return combinations.Concat(combinations.Select(s => new string[] { x }.Concat(s)));
}
}
And the string-parsing one:
public static IEnumerable<IEnumerable<string>> Combinations(string str) {
return Combinations(str.Split(" "));
}
Upvotes: 0
Reputation: 24370
Haskell, just because it's beautiful (compared to the C-family at least) and you said any language:
combinations [] = [[]]
combinations (x:xs) = (combinations xs) ++ map (x:) (combinations xs)
Can be invoked like this:
combinations ["word1", "word2", "word3"]
or like this, if you really have to pass it a space-separated string:
combinations (words "word1 word2 word3")
Upvotes: 1
Reputation: 114579
A simple way is
1
to (1<<w)-1
inclusive where w
is the number of words.Upvotes: 0
Reputation: 786
Sounds like a homework problem.
Use string.split and then use two for loops.
var wordlist = "word1 word2 word3";
var words = wordlist.Split(' ');
var wordList = new List<string>();
for( var i=0; i<words.Length; i++ )
{
var currentWord = words[i];
wordList.add( currentWord );
for( var j=i+1; j<words.Length; j++ )
{
currentWord += " " + words[j];
wordList.Add( currentWord );
}
}
You might also use string.Format or a StringBuilder if you want to be Melvin and get extra credit...
Upvotes: 0