Skip to content

Instantly share code, notes, and snippets.

@starius
Created April 17, 2016 16:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starius/b7bddaabca37ac6aea1ffc73125668a7 to your computer and use it in GitHub Desktop.
Save starius/b7bddaabca37ac6aea1ffc73125668a7 to your computer and use it in GitHub Desktop.
local function sample(it, count, random)
local answer = {}
do
-- first element
local element = it()
if element == nil then
return answer
end
answer[1] = element
end
for i = 2, count do
local element = it()
if element == nil then
return answer
end
local j = random(1, i - 1)
answer[i] = answer[j]
answer[j] = element
end
local i = count + 1
while true do
local element = it()
if element == nil then
return answer
end
local j = random(1, i - 1)
if j <= count then
answer[j] = element
end
i = i + 1
end
end
return sample
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment