David
David

Reputation: 163

parse out all combinations of words

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

Answers (4)

Jakob
Jakob

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

Jakob
Jakob

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

6502
6502

Reputation: 114579

A simple way is

  1. Count from 1 to (1<<w)-1 inclusive where w is the number of words.
  2. For each of the values of the counter consider the individual bits of the value, if the n-th bit is set then consider the n-th word, otherwise skip it.

Upvotes: 0

Sean
Sean

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

Related Questions