Quick question: Would this work?

Heyyo.
Just a quick question today.

So im try to make something that would shuffle the table provided around
image

Would this work? it fairly simple but i am flaming garbage at coding so
Also is there a better way to do this?

Thanks!!!
sparkynoob

3 Likes

I’m not sure, the one thing that I could see being a problem is that you set tab[i] to tab[n], then you set tab[n] to tab[I]. Say tab[i] was equal to “A” and tab[n] was equal to “B” could the following happen:

1:
tab[i] becomes tab[n]
now tab[n] is "B" so:
tab[i] becomes "B"

2:
tab[n] becomes tab[i]
now we just set tab[i] to be equal to "B" therefore:
tab[n] also becomes "B",
--and we end up with both becoming "B" instead of "A" and "B"

I guess all you can do is test it with prints and see if it works.

1 Like

No this would not because you can't just say tab[i], tab[n] = tab[n], tab[i] because the script is just like “yeah what about it” but the point is that that statement doesn’t do anything.

1 Like

I believe this would work because it looks similar to unpacking a tuple. The following works for sure:

local function test()
     return "A", "B", "C"
end

local a, b, c = test()
print(a, b, c) -- prints "A B C"

The question is whether it applies to your scenario. I would say yes, it should. Just make sure to put local in front unless you want them to be global.

1 Like

You can swap doing as you are perfectly fine. Evaluation occurs before assignment. On the right side tab[n] and tab[i] are evaluated before being assigned to the left side. This method is effectively swapping pointer locations.

The largest issue you will run into is that [i] and [n] can be the same since you don’t have a check for that. You could in theory end up having a table of duplicate values instead of a shuffled table. To remedy this you would want a range increased by i as the minimum.

for i = 1, #tab - 1 do
    local n = math.random(i, #tab)
    tab[i], tab[n] = tab[n], tab[i]
end
1 Like

Are you trying to make something similar to the Fisher Yates shuffle?

local RNG = Random.new()
local function shuffle(array)
	local a = #array
	for b = 1, a-1 do
		local c = RNG:NextInteger(b,a)
		array[b], array[c] = array[c], array[b]
	end
end
local num = {1,2,3,4,5,6,7,8,9,0}
shuffle(num)
print(num)
-- output: {
                    [1] = 2,
                    [2] = 1,
                    [3] = 3,
                    [4] = 4,
                    [5] = 5,
                    [6] = 8,
                    [7] = 0,
                    [8] = 7,
                    [9] = 6,
                    [10] = 9
                 }
2 Likes