Tech News
← Back to articles

Math Not Required (2023)

read original related products more articles

Let's examine a problem that we could math our way out of, but assume we don't know how. We'll lean on our programming to teach us what we don't know.

The Monty Hall problem comes from an old game show called Let's Make a Deal, hosted by Monty Hall. In the show, Monty would show three closed doors to a contestant and explain that one holds a car while the other two hold goats. The contestant then chose a door. After this first pick, Monty would reveal one unchosen door that was hiding a goat. The contestant then faced a key second choice: keep their door or switch to the other closed door. After this final choice, the two doors were opened and the contestant kept whatever they selected. The goal, of course, was to win a car.

What we really to want to know: are the chances of winning better if we switch or don't switch after the reveal?

Let's see if we can find out by modeling the problem in code:

defmodule MontyHallProblem do def dont_switch do Enum . at(randomize_doors(), pick_door()) # no need to model the reveal or second choice in this case since it # doesn't change the outcome end def switch do game = randomize_doors() pick1 = pick_door() reveal = 0 .. 2 |> Enum . filter( fn i -> i != pick1 and Enum . at(game, i) == :lose end ) |> Enum . random() pick2 = hd([ 0 , 1 , 2 ] -- [pick1, reveal]) Enum . at(game, pick2) end defp randomize_doors, do : Enum . shuffle( ~w[win lose lose]a ) defp pick_door, do : Enum . random( 0 .. 2 ) end

Hopefully this code is a pretty direct translation of the earlier problem description. Note that we now have two public functions, one that simulates a game where we switch and another for when we don't.

Here's a random run of each one:

MontyHallProblem . dont_switch() |> IO . inspect()

:win

MontyHallProblem . switch() |> IO . inspect()

... continue reading