Last active
August 28, 2018 12:32
-
-
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.
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
#!/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