However, in all likelihood a lot of people came up with this approach over the years. The data structure is explained in the first link, and was (officially) introduced to CompSci (as in, described in an academic publication) in the paper in the second link. ![]() It looks like your approach has a lot of overlap with this data structure (which specializations specific to your use-case). Since one swap per insertion is enough, picking a random item from our bag is O(1) instead. ![]() Using a shuffle vector, you can add elements by push, and grab a random element with pop. One very naive way to do it would be to shuffle the bag every time you pick an element, which as mentioned is O(n). > This may have benefits in some situations: if you have a "random bag" where you often add a few elements at a time, then want to pick elements at random. The difference is that instead of initiating the vector, then shuffling the whole thing, the shuffling is applied "lazily" as you add elements to it. ![]() Big-O is the same when you want to shuffle a whole array of n elements at once, namely O(n). > From a CompSci angle: this is a data-structure with a built-in Fisher-Yates shuffle. That the shuffle vector is a data structure that shuffles upon push/pop while still maintaining O(1):
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |