First Monday of Any Month to a Playing Card

•July 3, 2015 • Leave a Comment

The next step in associating every week in a year with a unique playing card is mentally calculating the first Monday of any month. Our cards will always denote Mondays, for a reason we’ll get to in a minute.

Use the century 1900 because its century number is 0 and we can ignore it, except for Jan and Feb, which we must pretend belong to 1899. The year 1899 is 6 = 2 (for 1800) + 1 (99 mod 7) + 3 ((99 / 4) mod 7).

For this calculation, think of Monday as a 2 or 9. To find the day of the month for the first Monday, just subtract the month number from 2 or 9. Jan 1899 is 1 = 2 (Jan) + 6 (1899) = 8 = 1, so the first Monday in Jan 1900 is 1 Jan. Cool! That’s why we’re going to reckon all our cards from Monday instead of from Sunday or Saturday.

Feb 1900 = Feb 1899 (pretend) = 4 = 5 (Feb) + 6 (1899) = 11 = 4. Subtract from 9. First Monday in Feb 1900 is 5 Feb.

Now it gets much easier for Mar through Dec because we don’t need to carry around the 6 for the pretend century.

First Monday in Jan is 1 Jan
First Monday in Feb is 5 Feb
First Monday in Mar is 9 – 4 (Mar) = 5 Mar
First Monday in Apr is 2 – 0 = 2 Apr
First Monday in May is 9 – 2 = 7 May
First Monday in Jun is 9 – 5 = 4 Jun
First Monday in Jul is 2 – 0 = 2 Jul
First Monday in Aug is 9 – 3 = 6 Aug
First Monday in Sep is 9 – 6 = 3 Sep
First Monday in Oct is 2 – 1 = 1 Oct
First Monday in Nov is 9 – 4 = 5 Nov
First Monday in Dec is 9 – 6 = 3 Dec

Now, starting with Jan and Spade A, count off the number of weeks in the months, which follow the amazing pattern 544/544/544/544. Count off cards in Black-Red-suit order (Spades, Hearts, Clubs, Diamonds) We get

First Monday in Jan is 1 Jan = Spade Ace
First Monday in Feb is 5 Feb = Spade 6
First Monday in Mar is 5 Mar = Spade 10
First Monday in Apr is 2 Apr = Heart Ace
First Monday in May is 7 May = Heart 6
First Monday in Jun is 4 Jun = Heart 10
First Monday in Jul is 2 Jul = Club Ace
First Monday in Aug is 6 Aug = Club 6
First Monday in Sep is 3 Sep = Club 10
First Monday in Oct is 1 Oct = Diamond Ace
First Monday in Nov is 5 Nov = Diamond 6
First Monday in Dec is 3 Dec = Diamond 10

Is that cool, or what?

How Rainman Computes Dates

•July 3, 2015 • Leave a Comment

Remember Dustin Hoffman’s character in the movie “Rainman,” who can instantly say the day of the week for a given date?  Of course, he was an autistic savant and probably didn’t know and certainly couldn’t teach how he does it, but here is a method I learned from my Dad.

Preliminaries:

Do all math mod 7, that is, you only need to keep the remainder of the results of any calculation after dividing by 7.  Thus, 15 is 1, 33 is 5, 49 is 0, etc.

Every day of the week has a number, starting with 1 for Sunday and ending with 0 for Saturday.  Your goal is to convert any Gregorian calendar date into such a number.

Jan and Feb belong to the year BEFORE. The reason is that leap years add a day at the end of Feb and it makes all the math easier to think that Jan and Feb 1963 are really part of 1962, for example.  Also remember that the Romans started their year with the month of March.  Maybe it was for a similar reason.

Example:

29 Nov 1872.

First convert the century.  1900 happens to be a 0, so that’s really really easy and convenient.  The numbers for all other centuries go in a cycle 6 4 2 0, which is also really easy to remember.  If you want peg words, say “ages run in sequence.”  To learn more about pegs, search for “peg” in my blog.  Because 1900 is 0, 2000 is 6, 2100 will be 4, 2200 will be 2, etc.  1800 is 2.

Keep 2 in your head and move forward.

Now convert the year, and there are two steps.  First, the year mod 7 because each year is one day longer than a multiple of 7, namely 364. 72 mod 7 is 2.  Add 2 to the 2 we’re carrying to get 4 so far.

Now get the number of leap years in the century.  That’s 72 / 4, or 18, which is 4.  Add it to the 4 we’re keeping, which is 8, which is 1.

Now get the month.  Here are peg mnemonics for months:

Mar    Irish          4  St. Patrick's Day
Apr    Easter         0
May    National       2  Memorial Day
Jun    Altar          5  Lots of weddings in June
Jul    Sun or Summer  0  First full sunny month of summer
Aug    Moon           3  Start seeing harvest moons in Aug
Sep    Job            6  Labor Day
Oct    Travel         1  Columbus Day
Nov    Restaurant     4  Eat turkey in a restaurant
Dec    Church         6  Christmas in a church
Jan    New            2  New-Year's Day
Feb    Love           5  St. Valentine's Day

If you forget one, you can recalculate a month number by just adding up the 30 = 2 and 31 = 3 days from the beginning of the year in March (mod 7, of course). The day counts for the months go like this: 32323/32323/30, nice easy pattern, or you can sing the “30 days hath September, April, June, and November” ditty if you prefer. Whatever works.

We’re carrying a 1 in head.  Add a 4 for Nov, giving 5.  Almost done.

29 mod 7 is 1; add our 5, we get 6.  29 Nov 1872 was a Friday.

Do this a few times and check yourself against Google or timeanddate.com.  You’ll make a few mistakes when getting started, but after a little while you’ll be able to do it quickly and reliably.

Remembering Dates

•June 30, 2015 • Leave a Comment

I find the most difficult memory task is to remember names.  I don’t know anything better than to search for some association between a person’s name and some distinguishing feature of the person’s visage that you can hook to the name.  Mr. Bromley has a moustache that looks like a broom.  That sort of thing.  It’s not easy, not quick, takes a lot of practice, and is especially hard with non-English names. In the real world, when I’m in a hurry and I haven’t had a chance to practice, I just use a lot of repetition, the old-fashioned, really error-prone, worst method.  But it’s so important that in any business meeting or party, unless I am the presenter, that’s the only thing I do — work on remembering everyone’s name.  It’s much more important than the content of the meeting or any drivel you hear at a party to remember everyone’s name.  I’m not fun at business meetings and parties, but the next time I meet those people and remember their names, they’re really impressed and they don’t forget ME, because I remembered them! Wow.

The second most difficult is to remember dates.  But there is an amazing coincidence and a powerful trick that makes this much easier.  There are 52 letters in the English alphabet, including both uncials (lower-case letters) and capitals.  There are 52 weeks in a year.  There are 52 cards in a standard card deck.  Can this get any easier?

Here’s a perpetual calendar, i.e., non-leap year, associated to cards in a deck, to ASCII codes, and to mental pictures.  Fill the out with your own tricks and stuff, and have fun!

|--------+----------+-----+-----+--------+-------+----+------+---------+
| PEG    | NATO     | WOY | DOY | DD-MMM | ASC   | UC | CARD | CARDSYM |
|--------+----------+-----+-----+--------+-------+----+------+---------+
| tea    | alpha    |   1 |   1 | 01 Jan | jail  | 65 | SA   | bat     |
| Noah   | bravo    |   2 |   8 | 08 Jan | judge | 66 | S2   | bean    |
| me     | charlie  |   3 |  15 | 15 Jan | chalk | 67 | S3   | beam    |
| ray    | delta    |   4 |  22 | 22 Jan | chef  | 68 | S4   | bar     |
| law    | echo     |   5 |  29 | 29 Jan | chip  | 69 | S5   | ball    |
| jaw    | foxtrot  |   6 |  36 | 05 Feb | case  | 70 | S6   | badge   |
| key    | golf     |   7 |  43 | 12 Feb | cat   | 71 | S7   | back    |
| fee    | hotel    |   8 |  50 | 19 Feb | can   | 72 | S8   | beef    |
| pea    | india    |   9 |  57 | 26 Feb | cam   | 73 | S9   | pipe    |
| toes   | julliet  |  10 |  64 | 05 Mar | car   | 74 | ST   | base    |
| tot    | kilo     |  11 |  71 | 12 Mar | coal  | 75 | SJ   | potato  |
| tan    | lima     |  12 |  78 | 19 Mar | cage  | 76 | SQ   | baton   |
| tam    | mike     |  13 |  85 | 26 Mar | cake  | 77 | SK   | podium  |
|--------+----------+-----+-----+--------+-------+----+------+---------+
| tar    | november |  14 |  92 | 02 Apr | cuff  | 78 | HA   | rat     |
| tail   | oscar    |  15 |  99 | 09 Apr | cap   | 79 | H2   | rain    |
| tissue | papa     |  16 | 106 | 16 Apr | face  | 80 | H3   | ram     |
| tack   | quebec   |  17 | 113 | 23 Apr | fat   | 81 | H4   | rear    |
| taffy  | romeo    |  18 | 120 | 30 Apr | fan   | 82 | H5   | rail    |
| tap    | sierra   |  19 | 127 | 07 May | fame  | 83 | H6   | rash    |
| nose   | tango    |  20 | 134 | 14 May | fare  | 84 | H7   | rack    |
| net    | uniform  |  21 | 141 | 21 May | fall  | 85 | H8   | reef    |
| nun    | victor   |  22 | 148 | 28 May | fish  | 86 | H9   | rope    |
| name   | whiskey  |  23 | 155 | 04 Jun | fig   | 87 | HT   | race    |
| nero   | x-ray    |  24 | 162 | 11 Jun | fife  | 88 | HJ   | ratatat |
| nail   | yankee   |  25 | 169 | 18 Jun | fob   | 89 | HQ   | rattan  |
| niche  | zulu     |  26 | 176 | 25 Jun | base  | 90 | HK   | radium  |
|--------+----------+-----+-----+--------+-------+----+------+---------+

 

|-------+-----+-----+--------+-------------+-----+------+------------|
| PEG   | WOY | DOY | DD-MMM | ASC         |  LC | CARD | CARDSYM    |
|-------+-----+-----+--------+-------------+-----+------+------------|
| neck  |  27 | 183 | 02 Jul | back        |  97 | CA   | cat        |
| navy  |  28 | 190 | 09 Jul | beef        |  98 | C2   | can        |
| nap   |  29 | 197 | 16 Jul | pipe        |  99 | C3   | cam        |
| mass  |  30 | 204 | 23 Jul | thesis      | 100 | C4   | car        |
| mat   |  31 | 211 | 30 Jul | toast       | 101 | C5   | coal       |
| man   |  32 | 218 | 06 Aug | dozen       | 102 | C6   | cage       |
| mama  |  33 | 225 | 13 Aug | twosome     | 103 | C7   | cake       |
| mare  |  34 | 232 | 20 Aug | dowser      | 104 | C8   | cuff       |
| mail  |  35 | 239 | 27 Aug | diesel      | 105 | C9   | cap        |
| match |  36 | 246 | 03 Sep | wood-sage   | 106 | CT   | case       |
| mike  |  37 | 253 | 10 Sep | tusk        | 107 | CJ   | cadet      |
| muff  |  38 | 260 | 17 Sep | adhesive    | 108 | CQ   | katana     |
| map   |  39 | 267 | 24 Sep | teaspoon    | 109 | CK   | catamaran  |
|-------+-----+-----+--------+-------------+-----+------+------------|
| race  |  40 | 274 | 01 Oct | tights      | 110 | DA   | tot        |
| rat   |  41 | 281 | 08 Oct | teetotaler  | 111 | D2   | tan        |
| rain  |  42 | 288 | 15 Oct | titan       | 112 | D3   | tam        |
| ram   |  43 | 295 | 22 Oct | totem       | 113 | D4   | tar        |
| rear  |  44 | 302 | 29 Oct | Tatar       | 114 | D5   | tail       |
| rail  |  45 | 309 | 05 Nov | title       | 115 | D6   | tissue     |
| rash  |  46 | 316 | 12 Nov | death-watch | 116 | D7   | tack       |
| rack  |  47 | 323 | 19 Nov | hot-dog     | 117 | D8   | taffy      |
| reef  |  48 | 330 | 26 Nov | auto-da-fe  | 118 | D9   | tap        |
| rope  |  49 | 337 | 03 Dec | teddy-bear  | 119 | DT   | toes       |
| lace  |  50 | 344 | 10 Dec | dance       | 120 | DJ   | teetotaler |
| lot   |  51 | 351 | 17 Dec | doughnut    | 121 | DQ   | titam      |
| lane  |  52 | 358 | 24 Dec | Athenian    | 122 | DK   | totem      |
|-------+-----+-----+--------+-------------+-----+------+------------|

 

Memorizing the ASCII Codes

•December 14, 2013 • Leave a Comment

If you’re already an expert in the memory-peg system, memorizing the ASCII codes is a snap. Consider the following table

| tea    | alpha    | jail  | 65 | back        | 97  |
| Noah   | bravo    | judge | 66 | beef        | 98  |
| me     | charlie  | chalk | 67 | pipe        | 99  |
| ray    | delta    | chef  | 68 | thesis      | 100 |
| law    | echo     | chip  | 69 | toast       | 101 |
| jaw    | foxtrot  | chess | 70 | dozen       | 102 |
| key    | golf     | cat   | 71 | twosome     | 103 |
| fee    | hotel    | can   | 72 | dowser      | 104 |
| pea    | india    | cam   | 73 | diesel      | 105 |
| toes   | julliet  | car   | 74 | wood-sage   | 106 |
| tot    | kilo     | coal  | 75 | tusk        | 107 |
| tan    | lima     | cage  | 76 | adhesive    | 108 |
| tam    | mike     | cake  | 77 | teaspoon    | 109 |
| tar    | november | cuff  | 78 | tights      | 110 |
| tail   | oscar    | cap   | 79 | teetotaler  | 111 |
| tissue | papa     | face  | 80 | titan       | 112 |
| tack   | quebec   | fat   | 81 | totem       | 113 |
| taffy  | romeo    | fan   | 82 | Tatar       | 114 |
| tap    | sierra   | fame  | 83 | title       | 115 |
| nose   | tango    | fare  | 84 | death-watch | 116 |
| net    | uniform  | fall  | 85 | hot-dog     | 117 |
| nun    | victor   | fish  | 86 | auto-da-fe  | 118 |
| name   | whiskey  | fig   | 87 | teddy-bear  | 119 |
| nero   | x-ray    | fife  | 88 | dance       | 120 |
| nail   | yankee   | fob   | 89 | doughnut    | 121 |
| niche  | zulu     | base  | 90 | Athenian    | 122 |

It’s easy to construct mental images for these. For instance, for “W,” I picture a TEDDY-BEAR resting on a nicely made bed; there are FIGs and thistles around him (a reference to Edna St. Vincent Millay); There is a beautiful NAME card resting along side him leaning up against the pillow; and an elegant crystal glass with a touch of WHISKEY in it on the night-stand, and I can smell the Whiskey. Smells work really well for me — it’s my own little touch of synaesthesia. This little domestic scene is easy to remember. Whenever I need the ASCII code for “W,” I instantly smell “WHISKEY,” then see the TEDDY-BEAR (119, ASCII for uncial “w”) and the FIGs (87, ASCII for capital “W”). As a bonus, I see the NAME card (23) and am reminded that “W” is the 23-rd letter of the alphabet.

Another example: for “G,” a TWOSOME comes up to the GOLF tee with a siamese CAT following them. Easy peasy.

I left out of the table an additional set of keys that I use, but they only work for the first 22 letters and you have to be comfortable with Hebrew. One motivation for my learning Hebrew was my recognition the Hebrew origins of my beloved memory system. Here are my automatic Hebrew word pictures:

אריה  Aryeh    1 lion     tea     lion in a teacup
בית   Beit     2 house    Noah    booth or house on top of Noah's Ark
גמל   Gamal    3 camel    me      camels dancing on my shoulder in the mirror
דלת   Delet    4 door     ray     shining my laser ray on the door in the dark
הר    Har      5 hill     law     policeman stopping me from climbing the mountain
ורד   Vered    6 rose     jaw     Lurch has a rose clenched in his teeth
זהב   Zahav    7 gold     key     I unlock a box of gold with my key
חמור  Hamor    8 donkey   fee     I am shoving a pile of gold to the donkey driver as his fee
טייס  Tayas    9 pilot    pea     the cockpit is full of peas
יד    Yad     10 hand     toes    the woman is painting her toenails with her hand
כסא   Kiseh   11 throne   tot     Alice is sitting on a giant gold throne
לחם   Lehem   12 bread    tan     The tanning tray has a loaf of bread on it
מים   Mayim   13 water    tam     Orcas at Miami Sea World are tossing around a Tam-o-Shanter
נחש   Nahash  14 snake    tar     a snake is burning as he slithers across the hot tar
ספר   Sefer   15 book     tail    the tiger's tail acts like a bookmark
עין   Ayin    16 eye      tissue  she's crying at her sweet-16 party
פנים  Panim   17 face     tack    a picture of Liz Taylor is tacked to the wall
ציפור Tzipor  18 sparrow  taffy   the bird's feet are stuck in hot taffy
קוף   Qof     19 monkey   tap     chimps are dispensing the beer
ראש   Rosh    20 head     nose    Goliath's head in David's hand: giant nose
שלד   Sheled  21 skeleton net     A skeleton is chasing butterflies with his net
תנין  Tanin   22 gator    nun     A nun has an aligator on a leash

These are just bonus associations for the Hebrew enthusiast; not at all necessary for today’s topic.

Some blogging on GitHub

•December 21, 2012 • Leave a Comment

I’m experimenting with Octopress on GitHub… have already posted a couple of blogs over there (http://rebcabin.github.com)

Reactive Mouse Headings

•November 11, 2012 • Leave a Comment

Every now and then, one meets an interesting stranger on a plane and you have an impromptu pair-programming session. That’s what happened when I met @praeclarum (aka Frank Krueger) on a recent flight. We swapped knowledge about PID controllers and Rx, The Reactive Framework, and went to work on a little UI problem: identify the “heading” of the mouse.

Heading is normally expressed in degrees, with 0 to the East, 90 to the North, 180 West, and 270 South. We figured if we could track mouse deltas, dy and dx, then Atan2(dy, dx) would give us an angle that we could transform into a heading. The technique for tracking mouse deltas is a recurring theme in Rx. First, get an observable from system-supplied mouse-move events supported by WinForms:

    var mms = Observable
        .FromEventPattern<MouseEventArgs>(form, "MouseMove")
        ;

This observable will produce observations containing mouse coordinates relative to the windows form. We need deltas, and here is a standard way to get them:

    var headings = mms.Zip(mms.Skip(1), (@from, @to) => {
        var dx = @to.EventArgs.X - @from.EventArgs.X; 
        var dy = @to.EventArgs.Y - @from.EventArgs.Y;
        return new { dx = dx, dy = dy };
        });

Just refer to the mouse-move observable, mms, twice, once with a .Skip(1). That gives a pair of observable streams offset by one event, which we .Zip together through a binary function, represented by the lambda expression with arguments (@from, @to). In this binary function, just subtract the coordinates component-wise. The result is an observable of instances of an anonymous type with properties dx and dy.

Atan2(dy, dx) works in a right-handed coordinate system, yielding angles between -pi (-180 degrees) and +pi (+180 degrees). We’d rather have positive angles all the time, so we just add 2 pi and mod by 2 pi:

    Func<double, double, double> RadiansFromDyDx =
         (dy, dx) => ((Math.Atan2(dy, dx) + 2 * Math.PI) % 
             (2 * Math.PI));

Adding a version that yields degrees just so we can visually check a console log:

    Func<double, double, int> DegreesFromDyDx =
         (dy, dx) => ((int)(RadiansFromDyDx(dy, dx) * 180 / Math.PI));

Now we just modify our .Zip function so that it yields a bunch of data we can use down the line to render System.Drawing.Points in the form and log the degrees:

    var headings = mms.Zip(mms.Skip(1), (@from, @to) => {
        var dx = @to.EventArgs.X - @from.EventArgs.X;
        var dy = @to.EventArgs.Y - @from.EventArgs.Y;
        return new
        {   @from = new Point(@from.EventArgs.X, @from.EventArgs.Y),
            @to = new Point(@to.EventArgs.X, @to.EventArgs.Y),
            angle = DegreesFromDyDx(-dy, dx),
            heading = RotatedQuadrantFromDyDx(-dy, dx)
        };   });

Notice how we have accounted for the WinForms left-handed coordinate system simply by reversing the algebraic sign of dy, plus we have added a new function:

    Func<double, double, int> RotatedQuadrantFromDyDx =
        (dy, dx) => ((int)((Math.Atan2(dy, dx) + 9 * Math.PI / 4) 
            * 2 / Math.PI)) % 4;

wherein we add pi/4 (45 degrees) to the angle, so we can count as East all angles between -45 and 45, North as all angles between 45 and 135, and so on; then multiply by 4, divide by 2/pi, convert to int, and mod by 4 for safety, so we always get a number between 0 and 3: 0 for East, 1 for North, 2 for West, and 3 for South.

Now Subscribe a few observers: one that logs the angle and heading, but only when the angle changes:

    headings
        .Select(h => new { h.angle, h.heading })
        .DistinctUntilChanged(h => h.angle)
        .Subscribe(h =>
        {   Console.WriteLine("[{2}]: {0}, {1}", h.heading, h.angle,
                Thread.CurrentThread.ManagedThreadId);
        })
        ;

(I like to log threadId’s, too, since one can often be fooled about the thread that is running some piece of code. This must all be on the UI thread).

Another observer that draws fat colored lines, color depending on direction:

    var pens = new [] 
    {   new Pen(Color.FromKnownColor(KnownColor.Red), 10),
        new Pen(Color.FromKnownColor(KnownColor.Green), 10),
        new Pen(Color.FromKnownColor(KnownColor.Blue), 10),
        new Pen(Color.FromKnownColor(KnownColor.Orange), 10)
    };
    headings
        .Subscribe(h => g.DrawLine(pens[h.heading], h.@from, h.@to))
        ;

and one that draws text denoting the direction

    var headingNames = new [] {"E", "N", "W", "S"};
    headings   
        .Select(d => d.heading)
        .DistinctUntilChanged()
        .Subscribe(h =>
        {   g.FillRectangle(backgroundBrush, 
                textPoint.X, textPoint.Y, 48, 48);
            g.DrawString(headingNames[h], font, brush, textPoint);
        });
        ;

You’ll forgive my ham-handed UI coding: this was more-or-less thrown together on the plane. You can see the whole code at this gist.

Also, the headings are a little jumpy. We’d like to smooth them out… perhaps with a PID controller?

Monty Monte Carlo

•November 3, 2012 • 3 Comments

The Monty-Hall problem is a notorious mind-trap concerning conditional probabilities. You’re on a TV game show, and you get to choose one of three doors. Behind one of the doors is a car: the prize; behind the other two doors are goats: the booby prizes. After you choose your door, if you haven’t won, Monty Hall will open one of the other two doors and show you a goat. You now have one final chance to choose a closed door. At this point, one of the two remaining hides the car and the other hides a goat. The problem is whether you should change your original choice, or stick with the original choice. The mind trap is thinking that, when facing your final choice, you have a fifty-fifty chance of winning whether you change doors or stick with your original choice.

Rather than  detail the reasoning (the wikipedia article is fine for that), I’m going to write a little simulation that runs a large number of games and tracks the results for the two strategies. Amusingly, the reasoning will emerge as we write the simulation. This often happens: writing code forces you to understand the problem with sufficient clarity that you actually solve the problem in a mathematical way, by pure reason, in “closed form,” that obviates the need to do a simulation. Writing the simulation actually simulates the logic of the problem in your mind.

The distribution of outcomes is the same whether the car is behind door 1, door 2, or door 3, so it suffices to consider the one case where the car is behind door 1. Simulate your first choice with the following Mathematica function:

firstChoice[] := RandomInteger[{1, 3}];

which depends on the primitive RandomInteger. You win immediately if you choose 1, so Monty will always show you 2 or 3. Therefore, Monty’s choice does not depend on yours:

montyChoice[] := RandomInteger[{2, 3}];

Your final choice depends on your first choice, on Monty’s choice, and on your strategy. Model your strategy with a Boolean variable named switchQ. Use the primitive RandomChoice:

secondChoice[yourFirst_, montyChoice_, switchQ_] :=
   If[switchQ,
    (* choose between door 1 and whatever monty didn't choose *)
    RandomChoice[{1, 5 - montyChoice}], 
    yourFirst];

By gum, we see it, don’t we? If you switch, you get a fifty-fifty chance; if you don’t switch, you only get a 1/3 chance. Amazing, but true. But, not to be daunted by reason, we will plow ahead with the simulation!

We run a round of the Monte-Carlo simulation as follows:

round[switchQ_] :=
   With[{f = firstChoice[]},
    If[f === 1,
     1,
     secondChoice[f, montyChoice[], switchQ]]];

Do a run of 300,000 games, tallying the results with the Tally and Table primitives, which fill up an array with data and then analyze it (watch this blog for a beautiful reactive, online form of this, later on!)

Tally@Table[round[True], {300000}]
~~> {{1, 200042}, {3, 50033}, {2, 49925}}

Ok, so about 2/3 of the time we win if we switch. How about if we don’t switch?

Tally@Table[round[False], {300000}]
~~> {{2, 99826}, {1, 100023}, {3, 100151}}

Only win 1/3 of the time! You double your chances by switching, it isn’t even close.

We can write another version of the simulation that pedantically imagines that after choosing door 1, we continue with the game, insisting that Monty show us a goat and that we pick some other door. In this case, Monty’s choice does depend on our choice, since he won’t show us 1.

Oddly, in this version, with the switch strategy, we lose only if we originally pick the winning door, but that’s just 1/3 of the time, so we win 2/3 of the time. If we don’t follow the switching strategy, then we win 1/3 of the time. The results are identical, and the following variant of the Monte-Carlo simulation bears this out.

firstChoice[] := RandomInteger[{1, 3}];

montyChoice[yourFirst_] :=
  If[yourFirst === 1,
    RandomInteger[{2, 3}],
    (* else *) 5 - yourFirst];

secondChoice[yourFirst_, montyChoice_, switchQ_] :=
  If[switchQ,
    Switch[yourFirst,
     1, 5 - montyChoice,
     2, 1,
     3, 1],
    yourFirst];

round[switchQ_] :=
  With[{f = firstChoice[]},
    secondChoice[f,montyChoice[f], switchQ]];
 
%d bloggers like this: