没有重复的随机名称选择器?

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


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);

}


HUWWW
浏览 215回答 1
1回答

临摹微笑

例如,您可以通过存储您已经使用过的内容来确保没有重复项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) {&nbsp; &nbsp; int index = r.Next(0, names.Length);&nbsp; &nbsp; if (!alreadyUsed.Contains(names[index])) {&nbsp; &nbsp; &nbsp; &nbsp; alreadyUsed.Add(names[index]);&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine($"{names[index]} was added.");&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP