简体   繁体   中英

Generation of random capital letters in C# while checking to generate only one pair from each

Hi I'm trying to code basic console Pexeso game in C#. And I'm wondering how to generate one and only one pair of capital letters.

So far my code can genereate string with random capital letters but I don't know how to control it to generate only two and only two from each one.

        string chars = "AABBCCDDEEFFGGHHIIJJKKLL";
        var stringChars = new char[24];
        Random random = new Random();

        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[random.Next(chars.Length)];
        }

        string finalString = new String(stringChars);

        Console.WriteLine(finalString);

Thank you very much for your help.

You start off well by defining all items you want in your final sequence.

What you want to do next is not take items from that list (in a way that you can take them more than once) as you do now, instead you actually want to shuffle your list.

Imagine your letters are playing cards, and you take two full sets. You shuffle them, and you have a sequence of playing cards, in which every card appears exactly twice.

To shuffle your set of letters, or any given sequence, you can use the Fisher-Yates shuffle .

Something like this should do the trick:

for (int i = chars.Length - 1; i > 0; i--)
{
    char j = random.Next(i + 1);
    int temp = chars[i];
    chars[i] = chars[j];
    chars[j] = temp;
}

Now your finalString is no longer needed: the result you want is in your chars array.

One of the trivial solutions for your problem is using LINQ's method OrderBy with a random number:

string chars = "AABBCCDDEEFFGGHHIIJJKKLL";

Random random = new Random();
var shuffled = chars.OrderBy(c => random.Next(chars.Length));

string finalString = new string(shuffled.ToArray());

Console.WriteLine(finalString);

Sometimes you may see people using Guid instead of random numbers:

string chars = "AABBCCDDEEFFGGHHIIJJKKLL";

var shuffled = chars.OrderBy(c => Guid.NewGuid());

string finalString = new string(shuffled.ToArray());

Console.WriteLine(finalString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM