# Random number with given frequency of occurenc

## Recommended Posts

ZMaster    240
Hi, I'm facing the following problem: I want an event to happen only in a given percentage of cases. So let's say the event is "Hit enemy". Everytime the player attacks the enemy I want to call a function which returns a random value 0 - for "failed" or 1 for "hit". Given is the frequency of occurrence of "hit" (eg. 50%) which is variable and may be different for another set of attacks. Here's a possible distrubtion of return values, with a percentage of 50% and 10 attacks at all: | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | The same should work with, 20% or any other percentage: | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | I hope you understand what I want to archieve and can help me out with this... Thanks, ZMaster

##### Share on other sites
ascorbic    307
Not sure exact function name for rand(), but:

int hit(int percentageOf100){     if(rand()%100 < percentageOf100)          return 1;     return 0;}

Do you mean something else?

##### Share on other sites
Opwiz    348
Generate a random value between 0 and 1 and compare the value with the hitrate (e.g. rand_val >= 0.5 if you want 50% hitrate).

##### Share on other sites
TerranFury    142
Generate a random floating-point number between 0 and 1. You can do this by with
(double)rand()/(double)RAND_MAX
, in C/C++, or by using the appropriate libraries in whatever language you are using.

Then... want a 50% chance of something happening? Do it if this number between 0 and 1 is less than .5. Want a 75%? Do it if the number is less than .75. etc.

##### Share on other sites
werekarg    193
this means you need a function: f:[0..1]->{0,1} (function that takes real values in the 0..1 interval and return one of the 0 or 1 values). you may, of course, replace the [0..1] interval with an integer interval of your choice ([0..100] for example.

this function will look like (ugly ascii art ahead):

f(x)
^
|
1 ##### ##############
|
0------#####--------------#####-> x (0..100)

you may even code a graphic editor to edit such functions and export them.

is this what you have in mind?

##### Share on other sites
ZMaster    240
Great! Thank you all, this is exactly what I wanted to do!
And yes, it's C++ I was talking about...