Sign in to follow this  

Random number with given frequency of occurenc

This topic is 4549 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites

This topic is 4549 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this