1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <set>
#include <vector>
#include <functional>
#include <algorithm>
// take a set of values and pairs them up at random, without repeats.
template < typename T >
std::vector< std::pair<T,T> > make_unique_pairs( const std::set<T>& set )
{
std::vector< std::pair<T,T> > result ;
// make a vector of references to elements in the set
std::vector< std::reference_wrapper< const T > > seq( set.begin(), set.end() ) ;
// make a random permutation of the references
std::random_shuffle( std::begin(seq), std::end(seq) ) ;
// make pairs and place them into the result
for( std::size_t i = 0 ; i < seq.size() - 1 ; i += 2 )
result.emplace_back( seq[i], seq[i+1] ) ;
return result ;
}
#include <cstdlib>
#include <ctime>
#include <iostream>
int main()
{
std::srand( std::time(nullptr) ) ;
const std::set<int> values { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } ;
for( auto pair : make_unique_pairs(values) )
std::cout << pair.first << ',' << pair.second << '\n' ;
}
|