Hello,
I need to implement the following situation in C++:
I have a counter which I want to increment with a certain probability.
I am giving a pseudo code which will clear:

counter = 0;
prob = 0.5;
for i <- 1 to 100
if(prob) // want to increment the counter with probability=0.5
counter++;
else
// do nothing

Your help is highly appreciated!!!

probability of what? Apples are red? Sky is blue? Grass is yellow?

How is the probability variable calculated? Just a random number? So you want to increment the counter if there is a 50-50 chance of something happening?

If you want to compare the probability of whatever it is, you shouldn't use the == operator, instead do...

if ( fabs(prob) - 0.5 < 0.001 ) {
  counter++;
}

You can change 0.001 to a precision of your choice.

Apples are red,
The sky is blue,
If he posted using code tags I was happier too.

:P

Ohh...Sorry!!!
I forgot to mention about the probability>
Ok...Suppose I have a vector.
I want to push a value to the vector with a probability p = 1/(1+vector.size())
otherwise I don't push anything into the vector.

How to handle this situation???

That doesn't make sense either. Suppose vector.size() == 0 (an empty vector). 1/1 = 1. So are you going to push something onto the vector or not? If yes, then the next item will be 1/(1+1) = 1/2 = 0.5. Again yes. Third time is 1/3 = 0.3323. No can push. That means only 2 items can be pushed onto the vector.

I think that I am not able to clear myself!!!
Anyways...I will try again.
Forget about the previous prob=0.5
Suppose size = 0; then prob = 1/(1+size) = 1/1 =1........Push
size = 1; prob = 1/2=0.5.......that means 50% random chance of pushing
size=2; prob = 1/3 = 0.3..that means 30% random chance of pushing
and likewise
I have only this details!!!
The main concern is the decision based on the random choice according to the probability values.

There is no such thing as a 30% chance of pushing -- either its pushed or it isn't. I suppose you could generate a random number between 0 and 1 and if it is greater than 0.3 then push it.

OP solution:

inline // interval [0..1)
double drand()
{
    return ::rand()/(RAND_MAX+1.0); 
}
inline
int randincr(int& counter, double p)
{
    return drand() < p? ++counter: counter;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.