a bag from which pop() takes an item uniformly at random
More...
#include <ADS/queue/RandomQueue.h>
|
| using | Item = T |
| | the type of the items
|
|
| | RandomQueue (std::uint64_t seed=1) |
| | the empty queue, its draws from the seed
|
| bool | empty (void) const |
| | true if there is no item
|
| std::size_t | size (void) const |
| | the number \( n \) of items
|
| void | push (const T &x) |
| | puts \( x \) in, \( O( 1 ) \) amortized (Morin's add( x ))
|
| void | push (T &&x) |
| | puts \( x \) in, moved
|
| T | pop (void) |
| | takes out an item chosen uniformly at random and returns it, \( O( 1 ) \) (Morin's remove())
|
| const T & | sample (void) |
| | an item chosen uniformly at random, left in
|
| std::size_t | uniform (std::size_t n) |
| | a place uniform in \( [ 0 , n ) \), by the multiplication of Lemire
|
| void | clear (void) |
| | removes all the items
|
| const std::vector< T > & | items (void) const |
| | the items, in no order
|
template<class T>
class ADS::RandomQueue< T >
a bag from which pop() takes an item uniformly at random
◆ Item
◆ RandomQueue()
the empty queue, its draws from the seed
◆ clear()
◆ empty()
◆ items()
◆ pop()
takes out an item chosen uniformly at random and returns it, \( O( 1 ) \) (Morin's remove())
In pseudocode (Morin, exercise 2.2), \( A[ 0 .. n - 1 ] \) the items:
\[\class{pseudocode}{\begin{array}{r@{\quad}l}
1 & \textbf{function}\ \mathrm{pop}() \cr
2 & \quad j \gets \text{uniform in } \{ 0 , \ldots , n - 1 \} \cr
3 & \quad \mathrm{swap}( A[ j ] , A[ n - 1 ] );\ n \gets n - 1 \cr
4 & \quad \textbf{return}\ A[ n ]
\end{array}}
\]
- Precondition
- the queue is not empty
- Postcondition
- one item less
◆ push() [1/2]
puts \( x \) in, \( O( 1 ) \) amortized (Morin's add( x ))
◆ push() [2/2]
◆ sample()
an item chosen uniformly at random, left in
- Precondition
- the queue is not empty
◆ size()
the number \( n \) of items
◆ uniform()
a place uniform in \( [ 0 , n ) \), by the multiplication of Lemire
In pseudocode (Lemire, beyond the book), \( w \) the words of 64 bits of the generator:
\[\class{pseudocode}{\begin{array}{r@{\quad}l}
1 & \textbf{function}\ \mathrm{uniform}( n ) \cr
2 & \quad ( h , l ) \gets \text{the two halves of } w \cdot n \cr
3 & \quad \textbf{if}\ l < n\ \textbf{then} \cr
4 & \qquad t \gets ( 2^{64} - n ) \bmod n \cr
5 & \qquad \textbf{while}\ l < t\ \textbf{do}\ ( h , l ) \gets
\text{the halves of } w \cdot n \text{ for a new } w \cr
6 & \quad \textbf{return}\ h
\end{array}}
\]
- Precondition
- \( n > 0 \)
The documentation for this class was generated from the following file: