A little challenge for you lua wizards!
I have a table containing numbers 1-5 defined as such:
local t = {1,2,3,4,5}
I want to randomise the table so the numbers are in a different order. The tricky part is making sure no number is randomised back to the same spot. So, a good result would be 2,4,5,1,3 but a bad result would be 3,2,5,4,1 (2 and 4 are in their original positions)
I’m currently using the following function that simply swaps each number with a random other one.
local t = {1,2,3,4,5}
for n = 1, 5 do
local r = math.random(1,5)
t[n], t[r] = t[r], t[n]
end
Obviously, the challenge is not that hard but I want to get an elegant as possible solution without iterating through loops hundreds of times.
I look forward to seeing what you come up with!