Lua: Random: Percentage

Posted by jargl on Stack Overflow See other posts from Stack Overflow or by jargl
Published on 2010-06-06T22:31:45Z Indexed on 2010/06/06 22:42 UTC
Read the original article Hit count: 223

Filed under:

I'm creating a game and currently have to deal with some math.randomness.

As I'm not that strong in Lua, how do you think

  • Can you make an algorithm that uses math.random with a given percentage?

I mean a function like this:

function randomChance( chance )
         -- Magic happens here
         -- Return either 0 or 1 based on the results of math.random
end
randomChance( 50 ) -- Like a 50-50 chance of "winning", should result in something like math.random( 1, 2 ) == 1 (?)
randomChance(20) -- 20% chance to result in a 1
randomChance(0) -- Result always is 0

However I have no clue how to go on, and I completely suck at algorithms

I hope you understood my bad explanation of what I'm trying to accomplish

© Stack Overflow or respective owner

Related posts about lua