## Table of Contents

## Open Table of Contents

## Introduction

Math puzzles are fascinating, because they show, how creative and often unintuitive solutions to seemingly simple problems can be.

Often, when I’ve been shown the solution to such a puzzle - even if I understand the proof - I don’t feel very satisfied, because I want to see what it would look like in practice. Good thing I can code and in the following I will show the results of my simulation of a couple of fun math puzzles I found out about. Obivously we know what the result of the simulations are going to be, since they have been mathematically proven. Nevertheless, I find it very satisfying if you do not only prove something theoretically, but also show that it will pan out that way exactly in real life.

Disclaimer: I will not explain the puzzles in this post. I have linked to fantastic YouTube video explanations that you should watch first, if you don’t know about the puzzle.

*You can look at all of the code for this post in this repository: daniellionel01/math-puzzles*

## 100 Prisoners

Explanation by Veritasium: The Riddle That Seems Impossible Even If You Know The Answer

The 2 situations we will compare are…

- that all prisoners pick a box at random and
- that all prisoners start with the box that corresponds to their number and if that box does not contain their number, they go to the box that has the number they just found

For both situations we get the following output from our simulation:

```
$ deno run src/100-prisoners.ts
picking at random: 0.04%
strategize: 35.45%
```

We simulated the experiment with only 10 prisoners and 1 million iterations. We only took 10 prisoners, because if you calculate the probability for 100 prisoners, it comes out to be (1/2)^100 = 0.0000000000000000000000000000008. And this number is so small that most programs are going to have a problem getting to that kind of floating point accuracy. By comparison (1/2)^10 = 0.0098, which is much more manageable.

By simulating the experiment, you can clearly see that the strategy of following the numbers in the boxes until a prisoner has found his or her number, is extremely effective, compared to just picking boxes at random.

## Monty Hall Problem

Explanation by Numberphile: Monty Hall Problem - Numberphile

This problem was and still is very counterintuitive to me. It just seems like you hack reality.

The two situations we are simulating is picking a new door and not picking a new door.

The results of this simulation are the following:

```
$ deno run src/monty-hall.ts
without switching: 33.38%
with switching: 49.92%
```

This simulation was done with 1 million iterations. You can clearly see how not choosing to switch doors reduces your chances to 1/3, but choosing the other door will make your chance 50%.