Search code examples
luashufflerandom

How do you do the Fisher-Yates shuffle in Lua


I've been asking questions on random numbers, and I decide the Fisher-Yates shuffle would be the best option. I make a table 't'

t = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Now, how would I even shuffle these and be able to use them individually, for example generate the results in another table u

u = {}

Solution

  • NOTE: Check the other answer https://stackoverflow.com/a/68486276/1190388 which fixes an issue in the code snippet below as well as providing other alternatives

    If you do not have holes in your table:

    math.randomseed(os.time()) -- so that the results are always different
    function FYShuffle( tInput )
        local tReturn = {}
        for i = #tInput, 1, -1 do
            local j = math.random(i)
            tInput[i], tInput[j] = tInput[j], tInput[i]
            table.insert(tReturn, tInput[i])
        end
        return tReturn
    end