Skip to content

Instantly share code, notes, and snippets.

@woodRock
Last active August 28, 2018 12:32
Show Gist options
  • Save woodRock/1357977c84bc7406b233157f73930bbb to your computer and use it in GitHub Desktop.
Save woodRock/1357977c84bc7406b233157f73930bbb to your computer and use it in GitHub Desktop.
Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.
#!/usr/bin/env ruby
def random_element(stream)
size = stream.length
rnd = Random.rand(size)
return stream[rnd]
end
stream = [22,44,33,55]
for i in 0..1000
puts random_element(stream)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment