Big Fish Interview Question
SDE-2sCountry: United States
public static int f200(){
int i=1;
int ret=0;
while(i++<8){
ret+=f1();
ret<<1;
}
if(ret>=1 && ret <=200) {
return ret;
} else {
return f200();
}
}
import random as rd
def prob200(half):
if half >= 200:
return 0
#f1 can be replaced by this rd.randint(0, 1)
toss_value = f1()
# check if toss falls in this current half and then change the half for next recursion.
# we change half from 1, 2, 4, 8, 16, 36, 64, 128
result = toss_value*half + prob200(half<<1)
if result > 200:
return prob200(1)
else:
return result
for i in range(0, 10):
print(prob200(1))
In Ruby:
def f1
return Random.rand(2)
end
def f200
# this function makes use of the property that, if you throw away
# evenly distributed numbers, the rest of the numbers are still
# evenly distributed
while true do
max = 0
result = 0
effect = 1
while max < 200 do
random_bit = f1()
result += random_bit * effect
max += 1 * effect
effect *= 2
end
return result if result >= 1 && result <= 200
end
end
# checking the results:
tally = Hash.new(0)
10000000.times { r = f200(); tally[r] += 1 }
tally.keys().sort().each {|k| puts "#{k}\t#{tally[k]}"}
- baoxin.zhou January 04, 2016