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

问题描述

如果我有一个包含 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[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],}
Question = variations[math.random(1,6)](Question)