Iterate Through Collection Items in Random Order
Problem
You need to enumerate through all the items in a collection, but you don’t want to visit items in order.
Solution
Create the RandomIterator class shown below, and use it to store an ArrayList of randomly ordered items.
Discussion
By default, enumeration moves through the items of a collection in order from first to last. And while it’s easy to randomly select a single item in a collection using the Random class, it’s more difficult to randomly walk through all items in a collection and ensure that each one is visited only once.
The solution is the RandomIterator class shown below. It stores a private collection and inserts all items into that collection in a random order. You can then walk through ...
Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.