Lua: Random: Percentage

I am creating a game and am currently dealing with some math.randomness.

How I am not so strong in Lua, what do you think

  • Can you create an algorithm that uses math.randomwith a given percentage?

I mean this function:

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 idea how to do this, and I completely suck the algorithms

I hope you understand my poor explanation of what I'm trying to accomplish.

+3
source share
2 answers

With no arguments, the function math.randomreturns 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 just convert your "chance" to a number from 0 to 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 randomby 100 to compare with 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

- 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
+7

; math.random . 100 1 100, , :

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
+5

Source: https://habr.com/ru/post/1748775/


All Articles