范围1, 2, 3, 4, 5, 6, 7, 8
(如果更容易,则可以填充Lua表)
table = {1, 4, 3}
可能的随机选择应在之中2, 5, 6, 7, 8
。
在Python中,我用它来获取它:
possibleChoices = random.choice([i for i in range(9) if i not in table])
任何想法如何在Lua中实现相同?
Lua有一个非常小的库,因此您必须编写自己的函数来执行某些任务,这些任务会自动以许多其他语言提供。
解决此问题的一种好方法是编写一些可以解决部分问题的小函数,并将其合并到最终解决方案中。在这里,最好有一个数字范围,其中不包括某些数字,从中随机画出一个数字。范围可以通过使用以下range
函数获得:
-- Returns a sequence containing the range [a, b].
function range (a, b)
local r = {}
for i = a, b do
r[#r + 1] = i
end
return r
end
为了得到一个不包含某些数字的序列,seq_diff
可以编写一个函数。这个版本使用了一个member
功能:
-- Returns true if x is a value in the table t.
function member (x, t)
for k, v in pairs(t) do
if v == x then
return true
end
end
return false
end
-- Returns the sequence u - v.
function seq_diff (u, v)
local result = {}
for _, x in ipairs(u) do
if not member(x, v) then
result[#result + 1] = x
end
end
return result
end
最后,这些较小的功能可以组合为一个解决方案:
-- Returns a random number from the range [a, b],
-- excluding numbers in the sequence seq.
function random_from_diff_range (a, b, seq)
local selections = seq_diff(range(a, b), seq)
return selections[math.random(#selections)]
end
样本互动:
> for i = 1, 20 do
>> print(random_from_diff_range(1, 8, {1, 4, 3}))
>> end
8
6
8
5
5
8
6
7
8
5
2
5
5
7
2
8
7
2
6
5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句