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
|
#include <iostream>
#include <random>
#include <iomanip>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
const int route[6][7] =
{
{ 0, 4, 5, 6, 7, 1, 0 },
{ 0, 8, 9, 2, 10, 11, 0 },
{ 0, 1, 1, 2, 18, 0, 1 },
{ 0, 1, 13, 2, 3, 15, 0 },
{ 0, 1, 1, 2, 1, 0, 2 },
{ 99, 88, 1, 77, 2, 0, 66 }
};
// select two random numbers other than { 0, 1, 2 } from each row
// initialise a random number engine
// https://en.cppreference.com/w/cpp/numeric/random
std::mt19937 rng( std::random_device{}() ) ;
// for each row in the route
// range based loop: http://www.stroustrup.com/C++11FAQ.html#for
// auto: http://www.stroustrup.com/C++11FAQ.html#auto
for( const auto& row : route )
{
// print the items in the row
std::cout << "row [" ;
for( int v : row ) std::cout << std::setw(3) << v ;
std::cout << " ]" ;
// select two random numbers other than { 0, 1, 2 } from this row
// 1. make a copy of this row
// https://cal-linux.com/tutorials/vectors.html
std::vector<int> cpy( std::begin(row), std::end(row) ) ;
// 2. shuffle the copy randomly
// https://en.cppreference.com/w/cpp/algorithm/random_shuffle
std::shuffle( std::begin(cpy), std::end(cpy), rng ) ;
// 3. pick the first two values in the shuffled copy that are not in { 0, 1, 2 }
std::cout << " select " ;
int nselected = 0 ;
for( int v : cpy )
{
if( v != 0 && v != 1 && v != 2 )
{
if( nselected == 1 ) std::cout << " and " ;
std::cout << v ;
++nselected ;
if( nselected == 2 ) break ;
}
}
if( nselected == 0 ) std::cout << "nothing (did not find any suitable number)\n" ;
else if( nselected == 1 ) std::cout << " (found only one suitable number)\n" ;
else std::cout << '\n' ; // found two
}
}
|