-1

Possible Duplicate:
Algorithm to select a single, random combination of values?

This is an interview question i've seen online.

You have one billion numbers, implement getRandom() which returns a random number from them.

Constaints: 1. No duplicate returning value. 2. getRandom() will at most be invoked 100 million times. Then optimize for space.

How is this solution, and what are some better ones?:

Shuffle the array of numbers. Keep a counter starting at 0. Everytime the user calls getRandom, return the value at counter index. Increment the counter.

Community
  • 1
  • 1
Joe legrae
  • 137
  • 2
  • 4

1 Answers1

-1

Lets assume that you have a random function that returns 1 or 0 with equal probability. You can call this function 32 times to get a random number between 0 to 2^(32)-1. You can call this function 64 times to get a random number between 0 to 2^(64)-1.

Avi Cohen
  • 3,102
  • 2
  • 25
  • 26