Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random function: higher values appear less often than lower

Tags:

php

random

math

I have a tricky question that I've looked into a couple of times without figuring it out.

Some backstory: I am making a textbased RPG-game where players fight against animals/monsters etc. It works like any other game where you hit a number of hitpoints on each other every round.

The problem: I am using the random-function in php to generate the final value of the hit, depending on levels, armor and such. But I'd like the higher values (like the max hit) to appear less often than the lower values.

This is an example-graph:

Example graph

How can I reproduce something like this using PHP and the rand-function? When typing rand(1,100) every number has an equal chance of being picked.

My idea is this: Make a 2nd degree (or quadratic function) and use the random number (x) to do the calculation.

Would this work like I want?

The question is a bit tricky, please let me know if you'd like more information and details.

like image 854
OptimusCrime Avatar asked Apr 26 '12 11:04

OptimusCrime


2 Answers

Please, look at this beatiful article: http://www.redblobgames.com/articles/probability/damage-rolls.html

There are interactive diagrams considering dice rolling and percentage of results. This should be very usefull for you.

Pay attention to this kind of rolling random number:

roll1 = rollDice(2,  12);
roll2 = rollDice(2,  12);
damage = min(roll1, roll2);

This should give you what you look for.

like image 162
Serge Kuharev Avatar answered Oct 12 '22 23:10

Serge Kuharev


OK, here's my idea :

Let's say you've got an array of elements (a,b,c,d) and you won't to randomly pick one of them. Doing a rand(1,4) to get the random element index, would mean that all elements have an equal chance to appear. (25%)

Now, let's say we take this array : (a,b,c,d,d).

Here we still have 4 elements, but not every one of them has equal chances to appear.

  • a,b,c : 20%
  • d : 40%

Or, let's take this array :

(1,2,3,...,97,97,97,98,98,98,99,99,99,100,100,100,100)

Hint : This way you won't only bias the random number generation algorithm, but you'll actually set the desired probability of apparition of each one (or of a range of numbers).


So, that's how I would go about that :

If you want numbers from 1 to 100 (with higher numbers appearing more frequently, get a random number from 1 to 1000 and associate it with a wider range. E.g.

rand = 800-1000 => rand/10 (80->100)
rand = 600-800  => rand/9 (66->88)
...

Or something like that. (You could use any math operation you imagine, modulo or whatever... and play with your algorithm). I hope you get my idea.

Good luck! :-)

like image 37
Dr.Kameleon Avatar answered Oct 13 '22 00:10

Dr.Kameleon