Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Number generation Issues

Tags:

java

random

This question was asked in my interview. random(0,1) is a function that generates integers 0 and 1 randomly. Using this function how would you design a function that takes two integers a,b as input and generates random integers including a and b.

I have No idea how to solve this.

like image 534
user973931 Avatar asked Jun 18 '26 23:06

user973931


1 Answers

We can do this easily by bit logic (E,g, a=4 b=10)

  1. Calculate difference b-a (for given e.g. 6)
  2. Now calculate ceil(log(b-a+1)(Base 2)) i.e. no of bits required to represent all numbers b/w a and b
  3. now call random(0,1) for each bit. (for given example range will be b/w 000 - 111)
  4. do step 3 till the number(say num) is b/w 000 to 110(inclusive) i.e. we need only 7 levels since b-a+1 is 7.So there are 7 possible states a,a+1,a+2,... a+6 which is b.
  5. return num + a.
like image 155
CommonMan Avatar answered Jun 20 '26 13:06

CommonMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!