Lua Challenge

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!

1 Like

You could use standard fisher-yates shuffle, except when you choose a spot to swap the current index, if the number is unchanged, restrict the range to not include the possibility of swapping with itself. Something like this (idk, haven’t tested it):

for i = #t, 2, -1 do
  local j = math.random(1, t[i] == i and i - 1 or i)
  t[i], t[j] = t[j], t[i]
end
3 Likes