简体   繁体   English

在 C# 中生成随机大写字母,同时检查每个字母只生成一对

[英]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#.嗨,我正在尝试用 C# 编写基本的控制台 Pexeso 游戏。 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 .要打乱您的一组字母或任何给定的序列,您可以使用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.现在不再需要您的finalString :您想要的结果在您的chars数组中。

One of the trivial solutions for your problem is using LINQ's method OrderBy with a random number:您的问题的一种简单解决方案是使用带有随机数的 LINQ 方法OrderBy

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:有时您可能会看到人们使用Guid而不是随机数:

string chars = "AABBCCDDEEFFGGHHIIJJKKLL";

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

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

Console.WriteLine(finalString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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