FastPrepRevolver: Will the Next Shot Fire?

Revolver: Will the Next Shot Fire?

Tower Research Capital logoTower Research Capital● EasyINTERNPHONE SCREEN

Problem statement

A revolver has chambers chambers arranged in a ring. Two bullets are loaded into two different chambers, the cylinder is spun once, and the trigger is pulled. The gun does not fire, so the fired chamber was empty. The cylinder is not spun again: the next pull fires the next chamber in the ring.

bulletLayout says what you know about where the two bullets are:

  • "unknown": nothing. Every pair of chambers was equally likely.
  • "nonadjacent": the bullets are not in neighboring chambers. Every such pair was equally likely.
  • "adjacent": the bullets are in neighboring chambers. Every such pair was equally likely.

Two chambers are neighbors when they are next to each other in the ring, so the last chamber and the first one are neighbors too.

Return the probability that the next pull fires. Answers within 10^-9 of the exact value are accepted.

Function

nextShotProbability(chambers: int, bulletLayout: String) → double

Examples

Example 1

chambers = 6bulletLayout = "unknown"return = 0.4

This is the revolver question from the interview. The two bullets can sit in 15 pairs of chambers. The empty first shot rules out the 5 pairs that use the fired chamber, leaving 10. In 4 of them a bullet sits in the next chamber, so the probability is 4/10 = 0.4.

Example 2

chambers = 6bulletLayout = "nonadjacent"return = 0.5

Only 9 pairs keep the bullets apart. 3 of them use the fired chamber, leaving 6. The next chamber holds a bullet in 3 of those, the ones where the other bullet is 2, 3 or 4 chambers further on. The probability is 3/6 = 0.5.

Example 3

chambers = 6bulletLayout = "adjacent"return = 0.25

There are 6 pairs of neighboring chambers. 2 of them use the fired chamber, leaving 4. Only one of those has a bullet in the next chamber: the pair made of the next chamber and the one after it. The probability is 1/4 = 0.25.

Constraints

  • 4 <= chambers <= 1000
  • bulletLayout is "unknown", "nonadjacent" or "adjacent".

More Tower Research Capital problems

See Tower Research Capital hiring insights
Saved
public double nextShotProbability(int chambers, String bulletLayout) {
    // Write your code here.
}
Checking account…