简体   繁体   中英

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.

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. A Linked List has O(n) access to find an element and then O(1) in removing the item you just found.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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