Improvements for random selection function

This is a quick function I wrote to help me select random children from under a given Instance. The main issue is if the total amount of children is high and the number to choose is near said total amount (totalChildren * 0.75 < numToSelect < totalChildren) performance takes a hit as the code tries to randomly select children that have already been selected over and over again.

My idea is to exclude the currently selected children from the remaining we have to select from, but I don’t know how that would look coding wise. Any advice would be appreciated.

local RNG = Random.new();

function CommonFunctions:FindRandomChild(parent, numToSelect)
	local fullList = parent:GetChildren();
	local selectedList = {};
	
	if #fullList > 0 then
		if not numToSelect or numToSelect == 1 then
			return fullList[RNG:NextInteger(1, #fullList)];
		elseif numToSelect >= #fullList then
			return fullList;
		elseif numToSelect > 1 then
			for i = 1, numToSelect do
				local randomSelection = fullList[RNG:NextInteger(1, #fullList)];
				
				if not table.find(selectedList, randomSelection) then
					table.insert(selectedList, randomSelection);
				end
				
				task.wait();
			end
			
			return selectedList;
		end
	end
end

Remove from fullList every time a child is chosen instead of checking if selectedList already contains it. You wouldn’t have to check if it was in the list this way.

3 Likes