Lua: 如何打乱数组中的某些元素?

Lua: How do I shuffle certain elements in an Array?

如果我有一个 table 5 个字符串,但我只想打乱第二个、第三个和第四个字符串,我该怎么办?

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

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

你可以写

Question[2],Question[3],Question[4] = Question[3],Question[4],Question[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)