Right now I have a table full of items, and I would like to recolor them one by one randomly, however I don't want the script to waste time by selecting an item in the table that has already been selected. Not asking for someone to write a script, just give me a little information on how you would do it so that I can work on it myself.
Is it possible to pull a random item from a table, and not pull it again?
3 answers
The easiest way is probably to shuffle the table and then iterate through it, otherwise you'd need to keep track of what you've already picked somehow (which is of course also possible).
local RNG = Random.new()
function shuffle(t)
for i = #t, 1, -1 do
local rand =RNG:NextInteger(1, i)
t[i], t[rand] = t[rand], t[i]
end
end
local t = {1,2,3,4,5}
shuffle(t)
print(unpack(t))
bascialy this:
var = 0
--fires when supposed to
var = math.random(1,0)
if var = 0 then
--choose that one item
elseif var = 1 then
--choose other item
but this is different and its numbers, but its same concept.
Solution
If you use two different tables (the original one you are using and an empty one) you can prevent the code from picking the same parts again.
To choose random colors, I suggest using math.random() from the numbers 0 to 255 since these are the ranges of each RBG value, rather than picking a preset BrickColor
You can pick a random instance using math.random() as well, except instead of using 0 and 255, we use the parameters from the first array instance (1) to the end instance of the array (given by #array)
Next, we can insert a chosen part into the empty table using table.insert() and then subsequently remove it from the original table using table.remove() so it won't be picked again.
Finally, we can make the original table be the same as the now full table and reset the second table to be empty, in case we want to use the function again.
Finalized Code
local array = {workspace:WaitForChild("Part1"), workspace:WaitForChild("Part2"), workspace:WaitForChild("Part3")}
local prevent = {}
local function RandomColor()
for i = 1, #array do
local random0 = math.random(1, #array)
local random1 = math.random(0, 255)
local random2 = math.random(0, 255)
local random3 = math.random(0, 255)
array[random0].Color = Color3.fromRGB(random1, random2, random3)
table.insert(prevent, random0, array[random0])
table.remove(array, random0)
end
array = prevent
prevent = {}
end
RandomColor()
To call the above function, you would use RandomColor() since that's the name of the local function
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
Include the code you are using.