You are given a function biasedCoin() (or rand2()) that returns 0 or 1 with equal probability (i.e., 50% heads, 50% tails). Write a function that returns 1 with probability 75% and 0 with probability 25%.
We can use two independent calls to the unbiased coin to generate four equally likely outcomes: (0,0), (0,1), (1,0), (1,1). Assign three of these to 1 and one to 0 to get the desired probabilities.
intbiasedCoin(); // returns 0 or 1 with 50% probability
intrand75() {
int a = biasedCoin();
int b = biasedCoin();
if (a ==0&& b ==0) return0;
return1;
}
1
2
3
4
5
6
7
8
9
funcbiasedCoin() int { /* returns 0 or 1 with 50% probability */ }
funcrand75() int {
a:=biasedCoin()
b:=biasedCoin()
ifa==0&&b==0 {
return0 }
return1}
1
2
3
4
5
6
7
intbiasedCoin() { /* returns 0 or 1 with 50% probability */ }
intrand75() {
int a = biasedCoin();
int b = biasedCoin();
if (a == 0 && b == 0) return 0;
return 1;
}
1
2
3
4
5
6
funbiasedCoin(): Int = /* returns 0 or 1 with 50% probability */funrand75(): Int {
val a = biasedCoin()
val b = biasedCoin()
returnif (a ==0&& b ==0) 0else1}
1
2
3
4
5
6
7
8
9
10
11
defbiasedCoin():
# returns 0 or 1 with 50% probabilityimport random
return random.randint(0, 1)
defrand75():
a = biasedCoin()
b = biasedCoin()
if a ==0and b ==0:
return0return1
1
2
3
4
5
6
fnbiased_coin() -> u8 { /* returns 0 or 1 with 50% probability */ }
fnrand75() -> u8 {
let a = biased_coin();
let b = biased_coin();
if a ==0&& b ==0 { 0 } else { 1 }
}
1
2
3
4
5
6
7
8
9
functionbiasedCoin():number {
// returns 0 or 1 with 50% probability
return Math.random() <0.5?0 : 1;
}
functionrand75():number {
consta=biasedCoin();
constb=biasedCoin();
return (a===0&&b===0) ?0 : 1;
}