Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number generation from a vector of numbers

Tags:

c++

random

vector

I have a vector v = {1,5,4,2}. Now I want to write a function that returns a random pair of numbers from this vector. Example: {1,2},{4,4},{2,5},{5,1},{1,5},{2,2}....... I want this pair to be generated in a random manner. Any idea how to implement this ?

like image 935
spnsp Avatar asked Jan 20 '26 15:01

spnsp


1 Answers

auto pair = std::make_pair(v[rand() % v.size()], v[rand() % v.size()]);

is one way.

Switch out rand() to something from the new <random> library of C++11 if you require the generator to have better statistical properties: aside from the generator itself, the use of % can introduce a statistical bias.

like image 64
Bathsheba Avatar answered Jan 22 '26 06:01

Bathsheba