Lua: 随机数:百分比

4

我正在制作一个游戏,目前需要处理一些与math.random有关的问题。

由于我不太擅长Lua,您认为

  • 您能否编写一个使用给定百分比的math.random算法?

我的意思是像这样的函数:

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

然而我不知道该怎么继续,而且我完全不擅长算法

我希望你能理解我所尝试实现的内容,虽然我的解释不好

2个回答

9
没有传入参数时,math.random函数返回的数字范围是[0,1)。
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> =math.random()
0.13153778814317
> =math.random()
0.75560532219503

因此,将您的“机会”简单地转换为介于0和1之间的数字:即,

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

或者将random的结果乘以100,与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

请记住,math.random(0,100)将返回0到100之间的数字,因此有101个可能的数字之一,因此您的maybe函数中的x不再是百分比,而是101中的1次机会。 - Yves Dorfsman

7

我不建议在这里使用浮点数,而是建议使用带有整数参数和整数结果的math.random。如果你在1到100的范围内选择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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接