随机名称选择器是否重复?

时间:2018-07-31 07:29:30

标签: c# random draw

我正在从指定列表中创建一个简单的名称选择器。我应该如何修改它,使其不重复已经“挑选”的名称?

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"};

    Random rnd2 = new Random();
    Console.WriteLine("Az ID : '1' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

    Random rnd3 = new Random();
    Console.WriteLine("Az ID : '2' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

    Random rnd4 = new Random();
    Console.WriteLine("Az ID : '3' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

    Random rnd5 = new Random();
    Console.WriteLine("Az ID : '4' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

    Random rnd6 = new Random();
    Console.WriteLine("Az ID : '5' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);

    Random rnd7 = new Random();
    Console.WriteLine("Az ID : '6' eszköz nyertese: " + Names[rnd2.Next(0, Names.Length - 1)]);


    Console.ReadKey(true);
}

1 个答案:

答案 0 :(得分:0)

例如,可以通过存储List<string>中已经使用的内容来确保没有重复的内容:

string[] names = new string[] { "bob", "james", "tim", "amanda", "lisa" }
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($"{names[index]} was added.");
    }
}