Solution to: [Day 3: Drawing Marbles](https://www.hackerrank.com/challenges/s10-mcq-6/problem)

<h1 id="tocheading">Table of Contents</h1>
<div id="toc"></div>


- Table of Contents
- Math Solution
    - Facts
- Monte Carlo Solution
    - Imports
    - Constants
    - Auxiliary functions
    - Main


```javascript
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')
```


    <IPython.core.display.Javascript object>


This script contains 2 sections:
1. Math solution to the problem
2. Monte Carlo simulation of the problem

# Math Solution
A bag contains 3 red marbles and 4 blue marbles. Then, 2 marbles are drawn from the bag, at random, without replacement. 
If the first marble drawn is red, what is the probability that the second marble is blue?


## Facts
- 7 marbles in the bag
- 1st one is always red
- P(B)?

If the first one is always red, we don't calculate the probability of the 1st draw.
Thus, we use the 6 remaining marbles.
\begin{equation}
\large
P(B) = \frac{4}{6} = \frac{2}{3}
\end{equation}

# Monte Carlo Solution

## Imports


```python
from typing import List
import random
```

## Constants


```python
MARBLE_DICT = {
	'r'	:	3,
	'b'	:	4
}
FIRST_MARBLE = 'r'
SECOND_MARBLE = 'b'
```

## Auxiliary functions


```python
def create_marble_bag(marbles: dict) -> List[str]:
	"""Returns list of marbles to draw from."""
	bag = []
	for k, v in marbles.items():
		m = [k for _ in range(v)]
		bag += m
	return bag
```


```python
def remove_first_marble(bag: List[str], marble: str) -> List[str]:
	"""Returns bag after removing marble."""
	bag.remove(marble)
	return bag
```


```python
def check_second_marble(bag: List[str], marble: str) -> bool:
	"""Returns boolean if sample from bag is the marble."""
	return random.choice(bag) == marble
```


```python
def get_ratio(bag: List[str], marble: str, iterations: int) -> float:
	"""Returns ratio of times sample from bag is marble."""
	was_marble = 0
	for _ in range(iterations):
		if check_second_marble(bag, marble):
			was_marble += 1
	return was_marble / iterations
```

## Main


```python
def main():
	bag = create_marble_bag(MARBLE_DICT)
	bag = remove_first_marble(bag, FIRST_MARBLE)

	iterations =  1000000
	ratio = get_ratio(bag, SECOND_MARBLE, iterations)
	print(ratio)
```


```python
if __name__ == "__main__":
	main()
```

    0.665724


c02358eb71fb8b59b600a4b84cc8a278fa0c9c54
ipynb
Jupyter Notebook
statistics/10_days/11_day3drawingmarbles.ipynb
jaimiles23/hacker_rank
0580eac82e5d0989afabb5c2e66faf09713f891b
Apache-2.0
statistics/10_days/11_day3drawingmarbles.ipynb
jaimiles23/hacker_rank
0580eac82e5d0989afabb5c2e66faf09713f891b
Apache-2.0
statistics/10_days/11_day3drawingmarbles.ipynb
jaimiles23/hacker_rank
0580eac82e5d0989afabb5c2e66faf09713f891b
Apache-2.0
2021-09-22T11:06:58.000Z
2022-01-25T09:29:24.000Z
Qwen/Qwen-72B
1. YES
2. YES