一个范围,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实现同样的目标?
发布于 2020-11-03 21:36:21
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
https://stackoverflow.com/questions/64670059
复制相似问题