如果我有一个由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)