How to shuffle an array


  • In this tutorial i will show you how to shuffle an array. For example, {"hello", "world", "goodbye", "abcdef"} could get shuffled to {"goodbye", "hello", "abcdef", "world"}.


    local toShuffle = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}
    
    local function shuffleArray(arr)
        local arrCopy = {unpack(arr)}
    end
    

    What I am doing right now, is making a copy of the array, since random elements of the copy will be removed.

    local function shuffleArray(arr)
        local arrCopy = {unpack(arr)}
    
        for i = 1, #arr do
            local pos = math.random(#arrCopy)
            arr[i] = table.remove(arrCopy, pos)
        end
        return arr -- # Return arr back for convenience, it is now shuffled
    end
    

    table.remove(table, pos) removes and returns the element at position pos, and if there is a gap created by this removal, the elements to the right of the gap are shifted to the left to fill in the gap. The table length is also decreased. It is great that remove returns the removed value so we do not have to retreive it ourselves.

    local toShuffle = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}
    
    local function shuffleArray(arr)
        local arrCopy = {unpack(arr)}
    
        for i = 1, #arr do
            local pos = math.random(#arrCopy)
            arr[i] = table.remove(arrCopy, pos)
        end
        return arr -- # Return arr back for convenience, it is now shuffled
    end
    
    print(table.concat(shuffleArray(toShuffle), ", "))
    --> nine, six, five, four, ten, three, one, two, eight, seven
    

    Enjoy your shuffled array.


  • @sjr04Alt nice job incapaxian


  • @sjr04Alt Good simple tutorials.

    More suggestions similar to this.

    • Converting Arrays to Strings
    • Popping and Pushing
    • Shifting Elements
    • Slicing an Array
    • Sorting an Array

    They are all basic stuff but should be pretty helpful to beginner programmer.

Log in to reply
 

Looks like your connection to Scripting Helpers was lost, please wait while we try to reconnect.