|
ADS
Algorithms and Data Structures
|
The random queue of exercise 2.2 of Morin's book, beyond the book: a bag in which push() puts an item and pop() takes one out chosen uniformly at random among those inside, both in \( O( 1 ) \) amortized time. More...
#include "ADS/Contract.h"#include "ADS/Portable.h"#include "ADS/Wide.h"#include "ADS/dictionary/RandomHashing.h"#include <cstddef>#include <cstdint>#include <utility>#include <vector>#include "ADS/queue/impl/RandomQueue.tpp"Go to the source code of this file.
Classes | |
| class | ADS::RandomQueue< T > |
| a bag from which pop() takes an item uniformly at random More... | |
Namespaces | |
| namespace | ADS |
The random queue of exercise 2.2 of Morin's book, beyond the book: a bag in which push() puts an item and pop() takes one out chosen uniformly at random among those inside, both in \( O( 1 ) \) amortized time.
The items are the first \( n \) places of a std::vector, which grows by a constant factor; pop() draws a place \( j \) uniform in \( [ 0 , n ) \), swaps it with the last one and removes the last one, so that the order of the vector never matters and nothing moves but two items. The place is drawn by the multiplication of Lemire, the high half of the product of a word of SplitMix64 [see RandomHashing.h] and \( n \), with the rejection of the few words that would bias it, and no division in the common case (a division by \( n \) only when the low half falls below \( n \)); the generator is seeded, so that a run is reproducible. sample() reads an item at random without removing it.
Each item is equally likely: by induction, the items left after any sequence of operations are a uniform sample of those pushed, whatever their order in the vector, since the draw does not look at it.
The contracts [see Contract.h]: pop() and sample() need a queue that is not empty; pop() ensures one item less. The operations are defined in RandomQueue.tpp.