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.

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.