How to change all indexes in the table to random indexs

for example how to make

local a  = {
[1] = "b"
[2] = "aa"
[3] = "ads" 
}

change to something like

[1] = "aa"
[2] = "b"
[3] = "ads"
1 Like
local a  = {
[1] = "b"
[2] = "aa"
[3] = "ads" 
}

for i = 1, #a do
a[i] = a[math.random(1, #a)]
end
1 Like

image
(the first table is the original one it sorts itself when i use for i,v loop)
also

local a  = {
[1] = "b",
[2] = "aa",
[3] = "ads" 
}

for i = 1, #a do
a[i] = a[math.random(1, #a)]
end print(a)  -  Studio
  02:58:49.677   ▼  {
                    [1] = "aa",
                    [2] = "aa",
                    [3] = "ads"
                 }  -  Edit

so some stuff repeats

1 Like

loop takes random index from table

1 Like

You could do a Fisher-Yates shuffle:

Code:

local a  = {
	"b",
	"aa",
	"ads" 
}

local function shuffle(t)
	local j, temp
	for i = #t, 1, -1 do
		j = math.random(i)
		temp = t[i]
		t[i] = t[j]
		t[j] = temp
	end
end

shuffle(a)
print(a)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.