tags:

views:

95

answers:

2

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

+6  A: 

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
Mark Rushakoff
+3  A: 

I wouldn't mess around with floating-point numbers here; I'd use math.random with an integer argument and integer results. If you pick 100 numbers in the range 1 to 100 you should get the percentages you want:

function randomChange (percent) -- returns true a given percentage of calls
  assert(percent >= 0 and percent <= 100) -- sanity check
  return percent >= math.random(1, 100)   -- 1 succeeds 1%, 50 succeeds 50%,
                                          -- 100 always succeeds, 0 always fails
end
Norman Ramsey