【问题标题】:Lua: How do I shuffle certain elements in an Array?Lua:如何打乱数组中的某些元素?
【发布时间】:2021-06-10 23:32:52
【问题描述】:

如果我有一个 5 个字符串的表,但我只想随机播放第二个、第三个和第四个,我该怎么做?

Question = {“question here”,”resp1”,”resp2”,”resp3”,”answer”}

而且我只想将 resp1、resp2 和 resp3 的位置打乱。

【问题讨论】:

    标签: arrays lua shuffle fisher-yates-shuffle


    【解决方案1】:

    你可以写

    Question[2],Question[3],Question[4] = Question[3],Question[4],Question[2]
    

    例如,或任何其他排列。

    【讨论】:

      【解决方案2】:
      -- indices to pick from
      local indices = {2,3,4}
      local shuffled = {}
      -- pick indices from the list randomly
      for i = 1, #indices do
        local pick = math.random(1, #indices)
        table.insert(shuffled, indices[pick])
        table.remove(indices, pick)
      end
      
      Question[2], Question[3], Question[4] = 
         Question[shuffled[1]], Question[shuffled[2]], Question[shuffled[3]]
      

      因为你只有 3 个!排列你也可以简单地做这样的事情:

      local variations = {
        function (t) return {t[1],t[2],t[3],t[4],t[5]} end,
        function (t) return {t[1],t[2],t[4],t[3],t[5]} end,
        function (t) return {t[1],t[3],t[2],t[4],t[5]} end,
        function (t) return {t[1],t[3],t[4],t[2],t[5]} end,
        function (t) return {t[1],t[4],t[2],t[3],t[5]} end,
        function (t) return {t[1],t[4],t[3],t[2],t[5]} end,
      }
      Question = variations[math.random(1,6)](Question)
      

      【讨论】:

        猜你喜欢
        • 2016-01-28
        • 2014-12-08
        • 1970-01-01
        • 2011-09-01
        • 1970-01-01
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        相关资源
        最近更新 更多