Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Is there a built-in function to randomize lists/tables?

Asked by
P100D 590 Moderation Voter
9 years ago

I'd rather just call some randomize function on a list than have to create the function myself.

0
You could of looked it up, there IS a search bar on the top of the screen anyway. There is also google, and roblox wiki. EzraNehemiah_TF2 3552 — 9y
1
Lord, some people ask because they found nothing and just want to confirm that there is nothing. DigitalVeer 1473 — 9y
0
Well, just let the Moderation thing expire. EzraNehemiah_TF2 3552 — 9y

2 answers

Log in to vote
2
Answered by
Unclear 1776 Moderation Voter
9 years ago

Unfortunately, Lua does not have any built-in implementation of shuffle algorithms.

However, there are some easy ones that you can implement or find.

The Fisher-Yates shuffle algorithm is an efficient, reliable, and easy-to-implement algorithm for array randomization.

Here is my optimized implementation of Fisher-Yates in Lua. Feel free to use it as you wish. All you have to do is put the function somewhere and call it on a table in array form that you want to shuffle.

function shuffle(array)
    -- fisher-yates
    local output = { }
    local random = math.random

    for index = 1, #array do
        local offset = index - 1
        local value = array[index]
        local randomIndex = offset*random()
        local flooredIndex = randomIndex - randomIndex%1

        if flooredIndex == offset then
            output[#output + 1] = value
        else
            output[#output + 1] = output[flooredIndex + 1]
            output[flooredIndex + 1] = value
        end
    end

    return output
end
math.randomseed(tick()) -- be sure to set randomseed somewhere for better randomness
0
Thanks! P100D 590 — 9y
Ad
Log in to vote
1
Answered by 9 years ago

There is no built-in function for randomizing a table. However, after a bit of research, I came across a script stickmasterluke posted.

The script essentially takes the values of a table, puts them in a new table in a random order using math.random and returns the new table once it's done. It even has example usage so you can figure out how it works.

You can take the script from here.

Answer this question