简体   繁体   English

C#从队列中随机选择一个项目

[英]C# pick a random item from a Queue

I wonder if it is possible to get a random item out of a queue?我想知道是否有可能从队列中获取随机项目?

Queue karten = new Queue();
        karten.Enqueue("Card 1");
        karten.Enqueue("Card 2");
        karten.Enqueue("Card 3");

        foreach(var x in karten)
        {
            Console.WriteLine(x);
        }

You are fundamentally missing the basics of OOP: use the appropriate data type for your purpose, and don't complicate stuff.您从根本上缺少 OOP 的基础知识:根据您的目的使用适当的数据类型,并且不要使事情复杂化。

List<string> list = new List<string>(); //this is an Array List
list.Add("One");
list.Add("Two");
list.Add("Three");

list.RemoveAt(new Random().Next(0, list.Length - 1));

If you need to access an item in possibly any place, you must use an array or array-backed list (as the C# List<T> ), which has O(1) complexity in accessing an element but O(n) in removal.如果您需要在任何地方访问项目,则必须使用数组或数组支持的列表(如 C# List<T> ),它在访问元素时具有 O(1) 复杂度,但在删除时具有 O(n) . A Linked List has O(n) access to find an element and then O(1) in removing the item you just found.一个链表有 O(n) 次访问来查找一个元素,然后 O(1) 来删除你刚刚找到的项目。

It means that if you use an array it takes a constant time to find an element by its index, but then you must shift the subsequent elements by one place.这意味着如果你使用一个数组,它需要一个常数时间来通过它的索引找到一个元素,但是你必须将随后的元素移动一个位置。 For the linked list, conversely, if you hold a reference to the item you want to remove, you take constant time in removing it.相反,对于链表,如果您持有对要删除项目的引用,删除它需要恒定的时间。 Of course, if you only know its position it takes O(n) to find the correct item first当然,如果你只知道它的位置,首先需要 O(n) 才能找到正确的项目

Here we are using a random input to remove the item.这里我们使用随机输入来删除项目。 In real life, you would expect a user input for choosing the item to remove: since that is not under your control, this falls into the random approach, where Array List succeeds在现实生活中,您会期望用户输入选择要删除的项目:因为这不在您的控制之下,这属于random方法,其中 Array List 成功

The logic you're describing don't match a Queue logic, for which the ordering of queued item is the base of the logic.您所描述的逻辑与队列逻辑不匹配,排队项目的排序是逻辑的基础。

You can use a standard list for the expected result.您可以对预期结果使用标准列表。

List<string> karten = new List<string>();
karten.Add("Karo 11");
karten.Add("Herz 2");
karten.Add("Herz König");
Random r = new Random();
    
while (karten.Count > 0)
{
    int i = r.Next(karten.Count - 1);
    Console.WriteLine(karten[i]);
    karten.RemoveAt(i);
}

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

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