Pregunta de entrevista de eBay

You are given a predefined function which generates random number from 1 to 5. You need to use this function and create another function which will generate random number from 1 to 7. Now most important thing is to remember that new random function should be even (i.e. the number generated should be unpredictable, and evenly spaced out).

Respuestas de entrevistas

Anónimo

9 abr 2011

Let f() be the random function that returns a number between (1,5). Let g() = f() -1; then g is a function that returns a number between (0,4). Let h() = g()/4; then h is a function that returns a number between (0,1). Let i() = h()*6; then i is a function that returns a number between (0,6) Let j() = i() + 1; then j is a function that returns a number between (1,7). important to note that simply multiplying by 7/5 is NOT correct. If you do that you can never get 1 out of your random number . the numbers you will obtain in that case will be uniformly distributed between (7/5 and 7) not between (1,7)

8

Anónimo

11 abr 2011

The answers where great but still not evenly distributed. There are chances to get even number more number of times then odd numbers and in some solution few numbers are never generated in random. I think the solution would be to the following steps 1) Combine the two possible number generated by random function with all possible combinations(i.e. 11,12,13,14,15,21,22.... 52,53,54,55). 2) With this we have total of 25 possible numbers. Now group all numbers in 7 groups, i.e. three numbers in one group and last group with 4 numbers {11,12,13} - group 1 ....... {44,45,51} group 7 {total numbers grouped till now is 21} and {52,53,54,55} - group 8. 3) call the random1to5() twice. 4) join two randomly generated number (e.g would be 11, 15, 55 etc) 5) Check in which group number lies, the group number will be the final random number. If the number lies in group 8 then ignore the number and re-run from step 3. I think this is evenly distributed and no chance of any number been superseded or more number of occurrence as compared to other number.

3

Anónimo

5 abr 2011

If the function returns float or double: - Simply multiply the answer by 7/5. If the function returns integers: - Call the rand5 function 7 times, sum the results, calculate mod7 of the sum and finally add 1.