Cracking Coding Interview - 6.7 the Apocalypse

The Apocalypse: In the new post-apocalyptic world, the world queen is desperately concerned about the birth rate. Therefore, she decrees that all families should ensure that they have one girl or else they face massive fines. If all families abide by this policy-that is, they have continue to have children until they have one girl, at which point they immediately stop-what will the gender ratio of the new generation be? (Assume that the odds of someone having a boy or a girl on any given pregnancy is equal.) Solve this out logically and then write a computer simulation of it.

Hints: #154, #160, #171, #188, #201

解法1

国家命令老百姓生孩子,而且一定要生一个女孩。现在已知生男生女的概率相同,都是50%,那么老百姓一直生,直到生到女孩为止,此时的男女比例是多少(排除掉父母计算)。

用B代表男孩,G代表女孩,P(B…G)代表某种生法的概率:

P(G) = 1/2(每个家庭必定有一个女孩,所以不存在P(B))

P(BG) = 1/22,第一个生男的概率是0.5,第二个生女的概率是0.5

P(BBG) = 1/23

整理一个表格:

男孩数量 概率 男孩数量 * 概率
0 1/21 0
1 1/22 1/22
2 1/23 2/23
3 1/24 3/24
4 1/25 4/25
5 1/26 5/26
6 1/27 6/27

那么平均下来每个家庭有几个男孩呢?把上面Sum(男孩数量 * 概率):

1
2
3
 1     2     3     4     5     6
-—- + -—- + -—- + -—- + -—- + -—-
 4     8     16    32    64   128

把分母都变成128然后计算:

1
2
3
 32    32    24    16    10    6    120
-—- + -—- + -—- + -—- + -—- + -—- = ---
128   128   128   128   128   128   128

接近1,所以平均下来每个家庭有1个男孩,那么因为已知每个家庭有1个女孩,那么男女比例接近1:1。男的1是到不了的,只能无限接近。

代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// n: 家庭数量
public double genderRatio(int n) {
  int boys = 0;
  int girls = 0;
  for (int i = 0; i < n; i++) {
    int genders = birth();
    boys += genders[0];
    girls += genders[1];
  }
  return boys / (double) girls;
}

public int[] birth() {
  int boys = 0;
  int girls = 0;
  Random random = new Random();
  while (girls == 0) {
    if (random.nextBoolean()) {
      girls++;
    } else {
      boys++;
    }
  }
  return new int[] {boys, girls};
}

版权

评论