Generating Random Letters
Posted
Tue, Mar 30 2010 19:46
by
Deborah Kurata
Someone recently posted in the forums the need to build a "Word Search" puzzle and wanted to generate a list of random letters.
.NET has all of the features you need to do this in just two lines of code.
In C#:
Random rand = new Random();
var letter = Enumerable.Range(0, 100).Select(
i => (char)((int)'A' + rand.Next(0, 26))).ToList();
In VB:
Dim rand As Random = New Random()
Dim letter = Enumerable.Range(0, 100).Select( _
Function(i) (Chr(Asc("A") + rand.Next(0, 26)))).ToList()
This code first created an instance of the Random class. It then builds the list of random letters.
The Range method on the Enumerable class defines the range of values, in this case the code generates 100 values, starting at 0. So if you need a different number of random values, this is the number you would change.
The Lambda expression uses the ASCII code for letters, adding a random value to "A" to get "A" through "Z". Finally, the code converts the set of letters to a list.
Use this technique whenever you need to generate a set of random letters.
Enjoy!
EDITED 4/1/10: Craig found a bug in the code above. rand.Next(0,25) picks a random number greater than or equal to 0 but LESS THAN 25. So to ensure that "Z" is also used, this needs to be changed to rand.Next(0,26). I corrected the code in both examples above. Thanks Craig!