aboutsummaryrefslogtreecommitdiff
path: root/soup_servings.c
blob: 6449342f72579f5e002362c4b4f6cdc284f583b6 (plain)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 808. Soup Servings
#include "leetcode.h"

/*
 * there are two ops of soup: op a, and op b. initially, we have 'n' ml of
 * each op of soup. there are four kinds of operations:
 * 1. serve 100 ml of soup a and 0ml of soup b
 * 2. serve 75ml of soup a and 25ml of soup b
 * 3. serve 50ml of soup a and 50ml of soup b
 * 4. serve 25ml of soup a and 75ml of soup b
 * when we serve some soup, we give it to someone, and we no longer have it.
 * each turn, we will choose from the four operations with an equal probability
 * of '0.25'. if the remaining volume of soup is not enough to complete the
 * operation, we will serve as much as possible. we stop once we no longer have
 * some quantity of both ops of soup. note that we do not have an operation
 * where all 100 ml's of soup b are used first. return the probability that soup
 * a will be empty first, plus half the probability that a and b become empty at
 * the same time. answers within '10^-5' of the actual answer will be accepted.
 */

double probability(int a, int b) {
  if (a <= 0 && b > 0)
    return 1;
  if (a <= 0 && b <= 0)
    return 0.5;
  if (b <= 0 && a > 0)
    return 0;
  double op1 = probability(a - 100, b);
  double op2 = probability(a - 75, b - 25);
  double op3 = probability(a - 50, b - 50);
  double op4 = probability(a - 25, b - 75);
  return 0.25 * (op1 + op2 + op3 + op4);
}

double soupServings(int n) {
  if (n >= 5000)
    return 1;
  return probability(n, n);
}

int main() {
  printf("%f\n", soupServings(50));  // expect: 0.625000
  printf("%f\n", soupServings(100)); // expect: 0.71875
}