0

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

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

我只想将 resp1、resp2 和 resp3 洗牌。

4

2 回答 2

2

你可以写

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

例如,或任何其他排列。

于 2021-03-13T00:43:56.240 回答
1
-- 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)
于 2021-03-13T08:23:45.823 回答