Skip to content

Instantly share code, notes, and snippets.

@tylerneylon
Created March 21, 2016 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerneylon/5ea37deecc087577d3ac to your computer and use it in GitHub Desktop.
Save tylerneylon/5ea37deecc087577d3ac to your computer and use it in GitHub Desktop.
Choose a uniformly random k-subset of [1,n] in O(k) time.
-- This returns a sequence of k distinct indexes in the range [1, n] chosen so
-- that, within the context of the pseudorandom generator, each k-subset has an
-- equal probability of being returned.
function random_indexes(k, n)
-- This is a partial Fisher-Yates shuffle, as suggested by this answer:
-- http://stackoverflow.com/a/29868630/3561
local shuf = {}
local indexes = {}
for i = 1, k do
local j = math.random(i, n)
shuf[i], shuf[j] = (shuf[j] or j), (shuf[i] or i)
indexes[i] = shuf[i]
end
return indexes
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment