Given a function for a fair coin, write a function for an offset coin?

I came across this reported interview question when doing some reviews (the following quote is all the information I found about the problem):

Given a function for a fair coin, write a function for an offset coin that returns heads 1 / n times (n is a pair)

At first glance, I wrote:

int biased_coin(n) { //0=Tails, 1=Heads
  int sum = 0;

  if(n==1)
    return 1;

  for(int i=0;i<n;i++) {
    sum += unbiased(); //unbiased returns 0 50% of the time and 1 50% of the time
  }

  if(sum == 1)
    return 1;

  return 0;
}

But this obviously does not work. For example, for n = 4 it works: since the probability of getting one head taking into account 4 volumes is 4 / (2 ^ 4) = 1/4. But for n = 3, 3 / (2 ^ 3)! = 1/3.

What is the right way to implement something like this if you cannot use a random number generator?

+5
source share
3 answers

Assuming that:

int fairCoinToss();

1 2 , :

int biasedCoinToss(int n);

(1) 1/n , :

int biasedCoinToss(int n) {
  if (n == 1) {
    return 1; // 1/1 = 1 = always heads
  } else if (n == 2) {
    return fairCoinToss(); // 1/2 = 50% = fair coint oss
  }
  int r = random_number(n);
  return r == 0 ? 1 : 0;
}

random_number(n) , 0 <= i < n. , random_number(3) 0, 1 2. , 0 1/3 .

, , . fairCoinToss() 1 0. . :

fairCoinToss() << 1 | fairCoinToss()

:

00 = 0
01 = 1
10 = 2
11 = 3

0 3 (n = 4).

, n -2, . , . , n = 5. 0 7. "" 5, 6 7, 0 4, () , 0 4 , .

:

int random_number(int n) {
  int ret;
  do {
    int limit = 2;
    ret = fairCoinToss();
    while (limit < n) {
      ret <<= 1;
      ret |= fairCoinToss();
      limit <<= 1;
    }
  } while (ret >= n);
  return ret;
}
+10

:
1. n 2. . .
3. , n, reeroll.
4. 0, .
5. .

+2

N 2, 1/N . , 1/N . , .

( H T), 2 node ( H T), , . ( ) , , , 1,2,3, N = 3. , , HHHTTHH ( - ). , "3".

.

0
source

All Articles