✓ Accepted answer
There are evidently many solutions to this problem, but I'll just share the first (and in my opinion, the simplest) that comes to mind.
Solution
You most likely don't want to change the state of the array whilst listing random indices, so you probably want some sort of buffer to temporarily represent the array. Then, a new table to store the new random configuration of the array.
local function randomSortArray(array)
local buffer = {}
for i = 1, #array do
buffer[i] = array[i]
end
local newArray = {}
while (#buffer > 0) do
newArray[#newArray+1] = table.remove(buffer, math.random(#buffer))
end
return newArray
end
Here's a Walkthrough
Create a clone of the original array (a buffer)
Copy all elements from array into the buffer
for i = 1, #array do buffer[i] = array[i]; end
Create a new empty table to store the random order of the array
Traverse the buffer, choose a random index, and insert that into the new array
newArray[#newArray+1] = table.remove(buffer, math.random(#buffer))
Return the new array
Notice that, while inserting the next random index to the new array, we're also removing it from the buffer. This is so that we update the probability according to the size of the array, while retaining it's array structure. I hope this helped. If you have any questions, just leave a comment and I'll get to it.
1 comment
This is a good question. Upvote this, people.