Pinball chute bounces
HardOnline Assessment
Find the expected number of ticks a pinball takes to fall out of a chute, as a value modulo 1,000,000,007.
A chute has n slots in a vertical line, numbered 1 (top) to n (bottom). A pinball starts in slot start. Every slot has a peg, and pegs[i - 1] = [a, b] describes the peg in slot i. Each tick, the ball in slot i is knocked by that slot's peg:
- with probability
a / bit drops one slot down; from slotnthat means it leaves the chute and the game is over; - otherwise (probability
1 - a / b) it is knocked one slot up; from slot1there is no slot above, so it bounces off the ceiling and stays in slot1.
The tick on which the ball drops out of slot n counts. Every peg has 1 <= a <= b, so each slot drops the ball with positive probability and the ball always gets out eventually. The expected number of ticks is a fraction P / Q; it can be astronomically large when pegs push mostly upward, so report it as P * Q^(-1) modulo 1,000,000,007, where Q^(-1) is the modular inverse. It is guaranteed that Q is not divisible by 1,000,000,007.
Input:
pegs: a non-empty list of[a, b]pairs, one per slot from top to bottom.start: the starting slot,1 <= start <= pegs.length.
Output: an integer from 0 to 1,000,000,006, the expected number of ticks modulo 1,000,000,007.
Setting up one equation per slot and solving the whole system the long way is too slow for a long chute; look for how the equations chain together.
Example 1
- Input:
- [[[1,1]],1]
- Output:
- 1
- Explanation
- There is one slot and its peg always drops the ball (probability 1/1). The ball leaves on the very first tick, so the expected number of ticks is 1.
Example 2
- Input:
- [[[1,2],[1,2]],1]
- Output:
- 6
- Explanation
- Let E1 and E2 be the expected ticks from each slot. From slot 2: E2 = 1 + (1/2)*0 + (1/2)*E1. From slot 1 the ball either drops to slot 2 or bounces and stays in slot 1: E1 = 1 + (1/2)*E2 + (1/2)*E1, so E1 = 2 + E2. Substituting gives E2 = 4 and E1 = 6.
Example 3
- Input:
- [[[3,4],[1,3]],2]
- Output:
- 666666677
- Explanation
- From slot 2: E2 = 1 + (2/3)*E1, and from slot 1: E1 = 1 + (3/4)*E2 + (1/4)*E1, so E1 = 4/3 + E2. Then E2 = 1 + (2/3)*(4/3 + E2), which gives E2 = 17/3. Reported modulo 1,000,000,007 that is 17 times the inverse of 3, namely 666666677.
Constraints
1 <= pegs.length <= 6001 <= a <= b <= 1,000,000for every peg[a, b]1 <= start <= pegs.length- the exact expected value has a denominator not divisible by
1,000,000,007