Lua:如何对数组中的某些元素进行随机排序?

如果我有一个包含5个字符串的表,但我只想随机重排第二个、第三个和第四个元素,我该怎么办?

Question = {“问题”,“回答1”,“回答2”,“回答3”,“答案”}

我只想随机交换resp1、resp2和resp3的位置。

点赞
用户107090
用户107090

你可以像下面这样写:

Question[2]、Question[3]、Question[4] = Question[3]、Question[4]、Question[2]

比如这样,或者任意其他排列。

2021-03-13 00:43:56
用户2858170
用户2858170

本地指数 = {2,3,4} 打乱后 = {}

对于 i = 1,#指数 do local pick = math.random(1, #indices) table.insert(打乱后, indices[pick]) table.remove(指数, pick) end

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

局部变量 = { 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 = variationsmath.random(1,6)

2021-03-13 08:23:45