PDA

View Full Version : Probabilities


Novo
04-20-2007, 03:07 PM
/****
table: { {item, unit}, {item, unit}, ... }

(+) getRandom( table )
- returns a given item from a list
(+) getProbability( table, item )
- calculates the probability of a given outcome
****/

public function getRandom( table )
{
if ( table.type() != 3 )
return false;

temp.total = 0;
for ( temp.tableCell: table )
temp.total += temp.tableCell[1];

temp.random = random(0, temp.total);
for ( temp.tableCell: table )
{
if ( temp.random < temp.tableCell[1] )
return temp.tableCell[0];

temp.random -= temp.tableCell[1];
}
return false;
}

public function getProbability( table, cell )
{
if ( table.type() != 3 )
return 0;

temp.probability = temp.total = 0;
for ( temp.tableCell: table )
{
temp.total += temp.tableCell[1];
if ( temp.tableCell[0] == cell )
temp.probability += temp.tableCell[1];
}

return ( temp.probability / temp.total );
}


Basically uses a probability table with a randomizer.

This is useful when you have a list of objects that carry different weight... And you want to select a random object.

One classical example would be mining: The the higher classed minerals have a lower rate of obtaining it.


mineTable = {
{"nothing", 50},
{"iron", 10},
{"gold", 3},
{"diamond", 1}
}

Nothing has a 50 in 64 chance of being seleted. iron, 10 in 64... etc etc.

I am planning on adding different probability functions to it later.

Chompy
04-20-2007, 04:04 PM
Very nice Novo :)

killerogue
04-20-2007, 07:55 PM
Excellent job here Novo!

It's really flexible in terms of uses. Like with the mine table or even a fish table.

But, a question, would running a for loop through your table and setting it as the second param net you different things from the table but make the most probable the one you get the most?

I'm at school and don't have the ability to test for another couple hours or so and was thinking about it, got very curious as to how I could work with that.

E: Also where'd you get the 64 max prob num from?

Chandler
04-20-2007, 08:26 PM
You released it! I like it, nice work!

Chompy
04-20-2007, 09:16 PM
E: Also where'd you get the 64 max prob num from?


mineTable = {
{"nothing", 50},
{"iron", 10},
{"gold", 3},
{"diamond", 1}
}


50 + 10 + 3 + 1 = 64

Probably from there :p