Title: Generate words of a given length in C#
The example Generate three-letter words in C# uses three nested for loops to generate words that contain three letters. This example uses the following code to generate words of any given length.
// Generate words with num_letters letters.
private List<string> GenerateLetterCombinations(int num_letters)
{
List<string> values = new List<string>();
// Build one-letter combinations.
for (char ch = 'a'; ch <= 'z'; ch++)
{
values.Add(ch.ToString());
}
// Add onto the combinations.
for (int i = 1; i < num_letters; i++)
{
// Make combinations containing i + 1 letters.
List<string> new_values = new List<string>();
foreach (string str in values)
{
// Add all possible letters to this string.
for (char ch = 'a'; ch <= 'z'; ch++)
{
new_values.Add(str + ch);
}
}
// Replace the old values with the new ones.
values = new_values;
}
return values;
}
The code first creates the 1-letter words a through z. Then for each additional letter that it must add, it loops through the existing words. For each existing word, the program loops through the letters a through z and creates a new word with that letter appended. For example, if the code is considering the existing word bad, it now creates the words bada, badb, badc, badd, and so forth.
The looping code adds the new words to a new List. When it's finished the code replaces the old values List with the new List. After it finishes building all of the strings, it returns the List.
Note: Don't run this example for very long strings, at least until you know how your computer will perform. The program generates 26N N-letter words so the number of words grows very quickly. For example, 265 = 11,881,376 and 266 = 308,915,776.
Download the example to experiment with it and to see additional details.
|