algorithm - LUA代码中如何保证表中相邻值不重复?

标签 algorithm lua

我目前正在处理一个 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/

相关文章:

c - 在 alpine 图像上构建 lua-openssl 时对 `strerror_s' 的 undefined reference

linux - lua-nginx 必须以 root 身份运行

c++ - 最小成本总和

Java树生成广度优先?

python - Python 中的字符串匹配

linux - 如何在 Linux 上获取/etc/ld.so.conf 中的路径列表

merge - 如何合并两个表并覆盖两个表中的元素?

c - 如何在编译时检查 liblua 版本?

string - 了解 Knuth-Morris-Pratt 算法

algorithm - 二叉树 : Non recursive routine to print ancestor of a node in a Binary Tree?