Problem 468485 · medium · Level 04 Non-Linear Data Structures

Caught Without an Umbrella

simulation · seeded random numbers · state · comparing with an exact answer

Mira owns k umbrellas, and they are all at home when she starts. She travels between home and her office, back and forth: trip 1 goes from home to the office, trip 2 back home, and so on. Before each trip it rains with probability p, independently of other trips. If it rains and there is an umbrella where she is, she takes one with her (so it ends up at the other place). If it rains and there is none, she gets wet. If it does not rain, she carries no umbrella.

Write wet_trips(k, p, trips, seed) that simulates trips trips with these rules:

  • Create one generator rng = random.Random(seed) and call rng.random() exactly once per trip, before the trip; it rains when the value is < p.

Return a tuple of three floats:

  1. the fraction of all trips on which she got wet,
  2. the fraction of the rainy trips on which she got wet (0.0 if it never rained),
  3. the exact long-run fraction of wet trips, p · (1 - p) / (k + 1 - p), which the first value should approach for many trips.

Examples

Input:  k = 1, p = 0.5, trips = 8, seed = 3
Output: (0.125, 0.25, 0.16666666666666666)
Explanation: the eight random numbers are 0.238, 0.544, 0.370, 0.604, 0.626, 0.066, 0.013, 0.837,
so it rains on trips 1, 3, 6 and 7. On trip 1 she carries the umbrella to the office, where it
stays during the dry trip 2, so on trip 3 (home again) she gets wet. On trip 6 she brings it
home and on trip 7 takes it back. Wet on 1 of 8 trips and on 1 of 4 rainy trips.

Input:  k = 2, p = 0.3, trips = 100000, seed = 2
Output: (0.07715, 0.25774229111682756, 0.07777777777777777)

Constraints

  • 0 <= k <= 20, 0 <= p <= 1, 1 <= trips <= 3 * 10**5, 0 <= seed < 2**32
  • floats are compared with a tolerance of 1e-6; use no randomness other than rng

Goals

  • Simulate a process whose state carries over from one step to the next
  • Use the random generator in exactly the prescribed way
  • Check a long-run simulated frequency against a known exact value
Starting Python…