【问题标题】:In this situation how can i display the results without duplicatin ?:)在这种情况下,我如何在没有重复的情况下显示结果?:)
【发布时间】:2018-07-31 09:16:06
【问题描述】:

我是初学者,请在婴儿级别上描述它......

static void Main(string[] args)
{
    string[] Names = { "Erik", "Levente", "Noel", "Áron", "Krisztián", "Kristóf", "Bence", "Roland", "Máté", "László", "Bálint" ,
    "Regina", "Brigitta", "Gréta", "Hédi", "Hanna", "Boglárka", "Jázmin", "Réka", "Alexandra", "Rebeka", "Lili", "Luca", "Zsófi"};          

    List<string> alreadyUsed = new List<string>();
    Random r = new Random();
    while (alreadyUsed.Count < Names.Length)
    {
        int index = r.Next(0, Names.Length);
        if (!alreadyUsed.Contains(Names[index]))
            alreadyUsed.Add(Names[index]);
        Console.WriteLine("The 1st Winner is:  " + Names[r.Next(0, Names.Length - 1)]);
    }

    Console.ReadKey(true);
}

【问题讨论】:

  • 您的实际问题是什么?代码的作用是什么?您期望的是什么?
  • 小心,你用一个随机数填充index,但在你的Console.WriteLine中你生成另一个随机数。这是你打算做的吗?

标签: c# random names


【解决方案1】:

如果你只是想显示没有重复的结果,那么试试:

while (alreadyUsed.Count < Names.Length)
{
    int index = r.Next(0, Names.Length);
    if (!alreadyUsed.Contains(Names[index]))
    {
        alreadyUsed.Add(Names[index]);
        Console.WriteLine("The 1st Winner is:  " + Names[index]);
    }
}

请注意,在Console.WriteLine 中,我使用的是当前添加的项目Names[index] 而不是Names[r.Next(0, Names.Length - 1)]

【讨论】:

  • 你不认为随机改组数组是一种更有效的方法吗?
  • @fubo 你的意思是Names.OrderBy(x =&gt; r.Next()).ToArray();?我认为是的,但 OP 只是询问是否显示没有重复的结果,所以我保持原样
【解决方案2】:

也许这个版本增加了一些可读性:

while (alreadyUsed.Count < Names.Length)
{
    var notUsedYet = Names.Except(alreadyUsed).ToArray();
    var index = r.Next(0, notUsedYet.Length);
    alreadyUsed.Add(notUsedYet[index]);
    Console.WriteLine("The 1st Winner is:  " + notUsedYet[index]);
}

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    相关资源
    最近更新 更多