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
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}
repeat
local newnumber = numbertable[math.random(1,#numbertable)]
if not table.find(scrambled,newnumber) then
table.insert(scrambled, newnumber)
end
until #scrambled == #numbertable
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