Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: Random: Percentage

Tags:

lua

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

like image 348
jargl Avatar asked Dec 06 '22 02:12

jargl


1 Answers

With no arguments, the math.random function returns a number in the range [0,1).

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> =math.random()
0.13153778814317
> =math.random()
0.75560532219503

So simply convert your "chance" to a number between 0 and 1: i.e.,

> function maybe(x) if math.random() < x then print("yes") else print("no") end end
> maybe(0.5)
yes
> maybe(0.5)
no

Or multiply the result of random by 100, to compare against an int in the range 0-100:

> function maybe(x) if 100 * math.random() < x then print(1) else print(0) end  end                                                                             
> maybe(50)
0
> maybe(10)
0
> maybe(99)
1

Yet another alternative is to pass the upper and lower limits to math.random:

> function maybe(x) if math.random(0,100) < x then print(1) else print(0) end end
> maybe(0)
0
> maybe(100)
1
like image 78
Mark Rushakoff Avatar answered Dec 28 '22 23:12

Mark Rushakoff