Matt McManis
Matt McManis

Reputation: 4675

Assign random letter to each variable

How can I cycle through variables and assign a random letter to each?

Without having to do:

var1 = RandomLetter();
var2 = RandomLetter();
var3 = RandomLetter();
var4 = RandomLetter();
var5 = RandomLetter();

This will produce all having the same letter:

var1 = var2 = var3 = RandomLetter();

I'm looking for a way to shorten the process, I need to do this to 50+ variables.

At first I though a foreach loop, but they are null and don't start out in a collection to loop through.

// Variables
public static char var1, var2, var3, var4, var5;


// Generate Random Letter
public static Random random = new Random();
public static char RandomLetter()
{
    const string text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int index = random.Next(text.Length);
    return text[index];
}

Upvotes: 0

Views: 238

Answers (2)

D Stanley
D Stanley

Reputation: 152501

Don't use separate variables, use a collection instead:

List<char> letters = 
    Enumerable.Range(1,50)
              .Select(i => RandomLetter())
              .ToList();

Upvotes: 5

Flater
Flater

Reputation: 13763

You can create an array of (irrelevant) numbers, and then convert every (irrelevant) number into a random character.

var randomLetterList = Enumerable.Range(0, 50)
                            .Select(x => RandomLetter())
                            .ToArray();

Enumerable.Range(0, 50)

This returns a list of 50 numbers, starting at 0: [ 0 , 1 , 2 , ... , 49 ]

.Select(x => RandomLetter())

This turns every element of the list into a random letter (notice that the actual value of the number is never used): e.g. [ 'b' , 'h' , 'm' , ... , 'o' ].

The important thing to note here is that the resulting list will contain exactly as many letters, as the initial list had numbers.

.ToArray();

This just converts the IEnumerable<char> into a char[]. This allows you to access the letters by using their index.

Instead of using

  • var1
  • var2
  • var3
  • ...
  • var50

you instead use:

  • randomLetterList[0]
  • randomLetterList[1]
  • randomLetterList[2]
  • ...
  • randomLetterList[49]

Upvotes: 1

Related Questions