Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I access 3 out of the 4 variables in this table?

I have a table that has 4 variables of 4 parts and I need it to be able to randomly select 3 out of those 4. How would I do that? Here are the variables and table. So how would I pick 3 out of the 4 of those randomly?

local blue = script.Parent.Blue

local green = script.Parent.Green

local yellow = script.parent.Yellow

local red = script.Parent.Red

local t = {blue, green, yellow, red}

2 answers

✓ Accepted answer
local ColorParts = script.Parent:GetChildren()


local Random3Parts = {} do
	---------------
	for _ = 1, 3 do
		---------------
		local RandomPart = ColorParts[math.random(1, #ColorParts)]
		---------------
		if (not table.find(Random3Parts, RandomPart)) then
			table.insert(Random3Parts, RandomPart)
		end
	end
end

Depending on the application, it might be better to just choose one part and then store the rest in a separate table. So instead of looping over each of the table's component you'd only need to loop n amount of times, with n being the amount of components you want to move to the another table.

Here's the concept with 4 components:

math.randomseed(tick()) -- Used to make the random() function more random
components = {"A","B","C","D"}
function randomlychoose(inputtable,n) -- function which will output a table of the components which were chosen
	local temptable = inputtable -- create a temporary copy of the inputted table
	local outputtable = {}
	for i = 1,n do
		r = math.random(1,#temptable) -- Create random number
		table.insert(outputtable,#outputtable + 1,temptable[r]) -- Add the randomly selected component to the output list
		table.remove(temptable,r) -- Remove the randomly chosen component, so that it can't be chosen again (and so that it can be outputted as well)
	end
	return temptable,outputtable
end

selection,rest = randomlychoose(components,1) -- choose one of the components to add to the 'selection', put the rest as the value of the 'rest' variable
print(selection[1]) -- prints the element which was 'selected'
print(rest[1],rest[2],rest[3]) -- print the first three elements of the 'rest' variable

Output:

B

A,C,D

Although this solution is quite more convoluted than what is needed, it will run quite efficiently no matter how many components you add to the list.

1 comment

0

That would significantly limit the number of random assortments.

This discussion is preserved as it was. New answers, comments, and votes are closed.