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

582 Views Asked by At

If I have a table of 5 strings but I only want to shuffle the second, third, and fourth, how would I go about it?

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

And I only want to shuffle resp1, resp2, and resp3 in their positions.

2

There are 2 best solutions below

0
On BEST ANSWER

You can write

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

for instance, or any other permutation.

0
On
-- 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]]

As you only have a 3! permutations you can also simply do something like this:

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)