BLOG.CSHARPHELPER.COM: Generate all possible three-letter words in C#
Generate all possible three-letter words in C#
This example uses the following very simple code to generate all of the possible three-letter words using the letters a through z.
// Make the items.
private void Form1_Load(object sender, EventArgs e)
{
List values = new List();
for (char ch1 = 'a'; ch1 <= 'z'; ch1++)
{
for (char ch2 = 'a'; ch2 <= 'z'; ch2++)
{
for (char ch3 = 'a'; ch3 <= 'z'; ch3++)
{
values.Add(ch1.ToString() + ch2.ToString() + ch3.ToString());
}
}
}
lstCombinations.DataSource = values;
lblCombinations.Text = values.Count + " combinations";
}
This code uses three nested loops to generate the letters. The outermost loop generates the first letter, the next loop generates the second letter, and the third loop generates the last letter. The result includes every possible combination in alphabetical order.
This example isn't very complicated. My next entry will show how to generalize this method to create words of any length. You might try to figure out how to do it yourself before you read that entry.
Comments