我目前正在处理一个 OpenVibe session ,我必须在其中编写一个 Lua 脚本。我的问题是生成一个包含 2 个值的随机表:1s 和 2s。如果表中的值为 1,则通过输出 1 发送刺激。如果为 2,则通过输出 2。
我的问题是如何在 Lua 代码中生成一个包含 52 个 1 和 2(44 个 1 和 8 个 2,对应 85% 1 和 15% 2)的表格,在下一个之前至少有 3 个 1 2秒?有点像这样: 1 1 1 2 1 1 1 1 1 1 2 1 1 1 1 2 1 1 1 2强>.
我不是 Lua 专家。因此,我们将不胜感激任何帮助。
最佳答案
local get_table_52
do
local cached_C = {}
local function C(n, k)
local idx = n * 9 + k
local value = cached_C[idx]
if not value then
if k == 0 or k == n then
value = 1
else
value = C(n-1, k-1) + C(n-1, k)
end
cached_C[idx] = value
end
return value
end
function get_table_52()
local result = {}
for j = 1, 52 do
result[j] = 1
end
local r = math.random(C(28, 8))
local p = 29
for k = 8, 1, -1 do
local b = 0
repeat
r = r - b
p = p - 1
b = C(p - 1, k - 1)
until r <= b
result[p + k * 3] = 2
end
return result
end
end
用法:
local t = get_table_52()
-- t contains 44 ones and 8 twos, there are at least 3 ones before next two
关于algorithm - LUA代码中如何保证表中相邻值不重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51025254/