hhh
BAN USER- 4of 4 votes
AnswersI Got this Crazy Question on PHONE INTERVIEW AT GOOGLE:
- hhh in United States
Design and implement a class to generate random numbers in an arbitrary probability distribution given by an array of integer weights, i.e. for int[] w return a number, n, from 0 to w.length - 1 with probability w[n] / sum(w). Using an existing random number generator with a uniform distribution is permitted.
Example distribution:
w = 1, 2, 3, 2, 1
Example probabilities:
w / sum = 1/9, 2/9, 1/3, 2/9, 1/9
Example results:
n = 0, 1, 2, 3, 4
Documentation:
Class java.util.Random
public int nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability.
Parameters:
n - the bound on the random number to be returned. Must be positive.
Returns:
the next pseudorandom, uniformly distributed int value between 0 (inclusive) and n (exclusive) from this random number generator's sequence
Throws:
IllegalArgumentException - if n is not positive| Report Duplicate | Flag | PURGE
Google Software Engineer / Developer Coding
In your solution, 1 more thing. We shouldnt hard code the distribution list "distro".
But, even then. You always assign float value. ie (1/9) etc.
There is no way you will get full values like (1,2,3) etc. Without multiplying it some value.
Your result will be list of floats.
RepEdithJHarden, Random at Axiom Sources
Je suis un professionnel de la gestion des soins de santé avec 2 ans d'expérience en supervision d'établissements ...
RepAvikaEthan, Data Engineer at Adjetter Media Network Pvt Ltd.
Avika Ethan has five years of experience collecting physical and biological data in California streams and rivers. In the field ...
When i meant "distro" should not be hard coded. i meant, it should be calculated rather than sent as an input.
- hhh April 12, 2013Also, your code, does return fractions. And not the desired output.
This is your output.
0.11172, 0.11111111
0.22012, 0.22222222
0.33512, 0.33333334
0.22142, 0.22222222
0.11162, 0.11111111