Question:
I’m trying to generate all possible word combinations using aList<string>
. For example, if I want to generate all possible word combinations of 2, the function would look like this:public static List
{
List
for (int i = 0; i < uniqueWords.Count; i++)
{
for (int j = 0; j < uniqueWords.Count; j++)
{
if (i != j)
{
unique2Words.Add(uniqueWords[i] + " " + uniqueWords[j]);
}
}
}
return unique2Words;
}
[/code]
Answer:
You can do this iteratively, with a single for loop, as follows.- Start with a list containing only the “empty sentence”.
- In each step, add each word to each previously constructed sentence.
Suppose
uniqueWords
is “a”, “b”, “c”.- At the start, you will have {“”}.
- After the first step, you will have {“a”, “b”, “c”}
- After the second step, you will have { “a+a”, “a+b”, “a+c”, “b+a”, “b+b”, “b+c”, “c+a”, “c+b”, “c+c”}
- After the third step, you will get { “a+a+a”, “a+b+a”, … }
The only modification required is then to filter out duplicates. This leads to something like this (unoptimized) example:
using System; using System.Collections.Generic;
public class SentenceGenerator
{
public static List> ExpandSentences(List
> partialSentences, List
{
var newSentences = new List>();
foreach(var sentence in partialSentences)
{
foreach(var word in uniqueWords)
{
if(sentence.Contains(word))
{
continue;
}
// Make a copy of the old sentence
var newSentence = new List
// Add a new word
newSentence.Add(word);
newSentences.Add(newSentence);
}
}
return newSentences;
}
public static void Main()
{
var uniqueWords = new List
“hello”,
“beautiful”,
“world”,
“full”,
“of”,
“people” };
var sentences = new List>() {
// Start with an empty sentence
new List
};
for(int i = 1; i <= 3; i++) { sentences = ExpandSentences(sentences, uniqueWords); } System.Console.WriteLine("Generated " + sentences.Count + " sentences."); foreach(var sentence in sentences) { System.Console.WriteLine(string.Join(" ", sentence)); } } } [/code]
Run it online (IDEOne)If you have better answer, please add a comment about this, thank you!