Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <random>
- using std::random_device, std::uniform_real_distribution; // <random>
- auto seed() -> auto { return random_device()(); }
- template< class URBG, class Func >
- void choose_randomly( const int n_values, const int range_size, URBG& bits, const Func& f )
- {
- uniform_real_distribution<double> random_from;
- int n_generated = 0;
- for ( int value = 0; value < range_size; ++value ) {
- const int n_to_generate = n_values - n_generated;
- const int n_remaining_values = range_size - value;
- if( random_from( bits ) <= 1.0*n_to_generate/n_remaining_values ) {
- f( value ); ++n_generated;
- if( n_generated == n_values ) {
- return;
- }
- }
- }
- }
- #include <algorithm>
- #include <iostream>
- #include <vector>
- using std::shuffle, // <algorithm>
- std::cout, std::endl, // <iostream>
- std::vector; // <vector>
- auto main() -> int
- {
- auto bits = std::mt19937( seed() ); //Standard mersenne_twister_engine.
- vector<int> key;
- const int n_key_items = 6;
- // Linear time generation of 6 random unique digits in sorted order.
- choose_randomly( n_key_items, 10, bits, [&key]( const int digit )
- {
- key.push_back( digit );
- } );
- // Linear time shuffling of the result sequence.
- shuffle( begin( key ), end( key ), bits );
- // Display it.
- for( const int v: key ) { cout << v << " "; }
- cout << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement