tags:

views:

49

answers:

1

I have a set like this:

set<vector<prmNode> > cammini

I need to take 2 random values (2 random vector) from this set. How could I do?? Thank you very much!

+1  A: 

The simplest solution would be to do the following twice.

*(std::advance(cammini.begin(), rand() % cammini.size()))

You can do it more efficiently if you generate two indexes, advance by the smaller and then advance by the difference between them.

avakar
Note that this is biased towards smaller indexes.
Joey
@Johannes, I don't think so. Can you elaborate?
avakar
Assuming `rand() % constant` is biased which it tends to be. The idea itself works, given non-biased random number generation, but a set is probably not a container of choice for picking random values out of.
UncleBens
Ah, of course, `rand() % k` is biased (regardless of the quality of `rand` itself), but it's the best one can do without involving Boost.Random or writing a non-trivial piece of code.
avakar
Unless `RAND_MAX` is an exact multiple of `cammini.size()` you will get the smaller indexes a little more often than the larger ones since you're using a modulus here. That's always the problem when using `%` to get a pseudo-random number up to *n*. It is less of a problem if `RAND_MAX` is larger but for some implementations it's ridiculously small. Basically you get (size/n) equal-sized intervals of *n* elements each and at the end of the `rand()` range one interval which is smaller. Every number falling into that last, smaller interval skews the distribution in your [0, *n*) interval.
Joey
Well, for a fairly concise and elegant piece of code how to deal with it, you could take a look at java.util.Random.nextInt(int). But yes, omitting such an elemental piece of functionality from C and even C++ is a bit frustrating at times.
Joey