Dokumentacja dla tego modułu może zostać utworzona pod nazwą Moduł:Losowe/opis

local p = {}

-- Algorytm wyboru liczb losowych na podstawie: https://www.codementor.io/@alexanderswilliams/how-to-efficiently-generate-a-random-subset-150hbz3na4
function p.wybierz(frame)
	math.randomseed(os.time())
	local preserve_order = false
	if frame.args['kolejność'] == 'tak' then
		preserve_order = true
	end
	local pick_count = tonumber(frame.args['liczba']) or 0
	
	local value_count = 0
	while frame.args[value_count+1] ~= nil do
		value_count = value_count + 1
	end
	
	if pick_count > value_count then
		pick_count = value_count
	end
	
	local indices = {}
	if pick_count < 0.63212055882 * value_count then
		indices = pickSmallCount(value_count, pick_count)
	else
		indices = pickLargeCount(value_count, pick_count)
	end
	
	if preserve_order then
		table.sort(indices)
	end
	
	local output = ''
	for i = 1, #indices do
		output = output..frame.args[indices[i]]
	end
	
	return output
end

function pickSmallCount(array_length, pick_count)
	local picked_map = {}
	local picked_indices = {}
	local picked_count = 0
	
	while picked_count < pick_count do
		local new_index = math.random(array_length)
		if picked_map[new_index] == nil then
			picked_map[new_index] = true
			table.insert(picked_indices, new_index)
			picked_count = picked_count + 1
		end
	end
	
	return picked_indices
end

function pickLargeCount(array_length, pick_count)
	shuffled = {}
	for i = 1, array_length do
		local pos = math.random(#shuffled+1)
		table.insert(shuffled, pos, i)
	end
	
	while #shuffled > pick_count do
		table.remove(shuffled, #shuffled)
	end
	
	return shuffled
end

return p