Nerd Paradise : Coding Interview 2: Get a Random Object from a Stream
Suppose you have a stream object. This stream object ONLY has two methods. They are:
function get_random_object(stream):
size = 1
object = stream.GetNext()
while stream.HasNext():
next = stream.GetNext()
// generate a random number from 1 to size + 1, inclusive
if random(1, size + 1) == 1:
object = next
size = size + 1
return object
Read full article from Nerd Paradise : Coding Interview 2: Get a Random Object from a Stream
Suppose you have a stream object. This stream object ONLY has two methods. They are:
- HasNext() - returns a boolean if there's more items in the stream
- GetNext() - returns the next item in the stream
function get_random_object(stream):
size = 1
object = stream.GetNext()
while stream.HasNext():
next = stream.GetNext()
// generate a random number from 1 to size + 1, inclusive
if random(1, size + 1) == 1:
object = next
size = size + 1
return object
Read full article from Nerd Paradise : Coding Interview 2: Get a Random Object from a Stream