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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
#include <iostream>
#include <random>
#include <iomanip>
#include <ctime>
// generate a random integer value in [min_value, max_value]
template < typename INT_TYPE >
INT_TYPE random_int( INT_TYPE min_value, INT_TYPE max_value )
{
// GNU/MinGW does not have a real random_device;
// so use a seed sequence which also has current time
static long long seeds[] = { std::random_device{}(), std::time(nullptr) } ;
static std::seed_seq sseq( seeds, seeds+1 ) ;
static std::mt19937 rng(sseq) ;
static std::uniform_int_distribution<INT_TYPE> distrib ;
using param_type = typename std::uniform_int_distribution<INT_TYPE>::param_type ;
return distrib( rng, param_type{ min_value, max_value } ) ;
}
// generate a random row having min_cols-max_cols columns
std::vector<int> make_random_row( std::size_t min_cols, std::size_t max_cols,
int min_value, int max_value )
{
std::vector<int> row ;
const std::size_t num_cols = random_int( min_cols, max_cols ) ;
while( row.size() < num_cols ) row.push_back( random_int( min_value, max_value ) ) ;
return row ;
}
// generate a random 2d vector
std::vector< std::vector<int> > make_random_vec_2d( std::size_t min_rows = 3, std::size_t max_rows = 5,
std::size_t min_cols = 1, std::size_t max_cols = 10,
int min_value = 0, int max_value = 10 )
{
std::vector< std::vector<int> > vec_2d ;
const std::size_t num_rows = random_int( min_rows, max_rows ) ;
while( vec_2d.size() < num_rows )
vec_2d.push_back( make_random_row( min_cols, max_cols, min_value, max_value ) ) ;
return vec_2d ;
}
void print( const std::vector< std::vector<int> >& vec2d )
{
for( const auto& row : vec2d )
{
for( int v : row ) std::cout << std::setw(3) << v << ' ' ;
std::cout << '\n' ;
}
}
int main()
{
const auto vec = make_random_vec_2d() ;
print(vec) ;
std::cout << "\n\n" ;
// 5-10 rows, 4-8 cols, values in [23,72]
const auto vec2 = make_random_vec_2d( 5, 10, 4, 8, 23, 72 ) ;
print(vec2) ;
}
|