LinkedList values = new((_ => rand.Next()) Ĭredit goes to for the simple shuffling code. dealing out more than log(n) of your "deck"), you'll be better off just shuffling your entire deck first, and then pulling from the top: public IEnumerable UniqueRandomValues(IDictionary dict) If, on the other hand, you're planning to pull a significant number of elements from your dictionary (i.e. TKey randomKey = (rand.Next(0, values.Count)) // hat tip randomValue = values The code for this would be a little more complicated, so if you're willing to sacrifice some performance for simplicity you could just do this: public IEnumerable UniqueRandomValues(IDictionary dict)ĭictionary values = new Dictionary(dict) You'll probably also want to make the list into a LinkedList, because even though it'll be slower to find an item by its index, it's much less expensive to remove elements from the middle of it. If you're only getting a few elements out of a large Dictionary, then you should be able to adapt my other answer, removing the random element from the list each time a new one is retrieved. In that case, the best strategy will depend on exactly what you're doing. Once a card is dealt, you never want to see the same card again until a re-shuffle. However, your comments make it sound like you might be hoping to get a series of "unique" elements out of the Dictionary, sort of like dealing cards from a deck. My other answer is correct for the question, and would be useful in many cases like getting roll information from custom dice (each die's roll is random, independent of the other dice). My tests show that with 1000 objects in the dictionary, this method goes about 70 times faster than the other suggested methods. Not as big a deal as #1, but it's still over twice as fast this way. It doesn't have to perform a lookup based on the Dictionary's key each time you fetch a random value. This is a really big deal if your dictionary has a lot of elements in it.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |