How to make a "number scrambler"

I’m trying to make this script take numbers in a table, and use math.random() to take a random number from the number table, and put it in another table

My Current Script is below:

local numbertable = {1,2,3,4,5,6}
    local scrambled = {}
    
    repeat
        local newnumber = numbertable[math.random(1,#numbertable)]
        if newnumber ~= scrambled[newnumber] then
            table.insert(scrambled, newnumber)
        end
    until #scrambled == #numbertable
    return scrambled

The script works in getting random numbers put into a table, but for some reason the “number checker”
if newnumber ~= scrambled[newnumber] then

doesnt seem to work.

I have also tried table.find() and that doesnt work, all it does it keep looping through a finished table and not moving on past the repeat until loop

Any help is fantastic!

1 Like

Try using yourTable[index: number] instead of table.find. Table.find is used in different cases than using brackets but I haven’t researched that much yet.

Edit: table.find is used for tables like this:

local myTable = {"a","b","c"}

while using brackets to find something in a table is used for tables that look like this, because there’s things to work with, an index and a value, unlike above, there’s just a value:

local myTable = {["a"] = 100,["b"] = 500,["c"] = 90}
1 Like

how would i replace that in form of the script

im not that really good with tables right now :sweat_smile:

1 Like

Alright so I have a solution:

    repeat
        local newnumber = numbertable[math.random(1,#numbertable)]

        if not table.find(scrambled,newnumber) then
            table.insert(scrambled, newnumber)
        end
    until #scrambled == #numbertable

that worked! thank you so much!!

1 Like

This might work better. It has a definitive complexity, whereas the current solution (though it works) could theoretically loop forever if the wrong random numbers keep occurring. Mine will loop once for every item in the table, guaranteeing that it always performs as fast as possible. The current solution can be this fast, but will almost always be slower.

local scrambled = {}
for _, v in numbertable do
    table.insert(scrambled, math.random(math.max(1, #scrambled)), v)
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.