Created
April 17, 2016 16:35
-
-
Save starius/b7bddaabca37ac6aea1ffc73125668a7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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