I was helping my daughter with some math homework; one of the problems was to flip three coins and tabulate the number of heads over the course of eighty trials. This struck me as excessively tedious, so I suggested we write a computer simulation instead.
Here it is, in its full glory:
coin := Random[Integer, {0, 1}]
flips := coin + coin + coin
Length /@ Split @ Sort @ Table[flips, {80}]
The code is written in the Mathematica language. The first two lines should be self explanatory. The last line is the workhorse; I'll illustrate how it works, but with only twenty trials so that results fit the screen better.
The code should be read from right to left. Table[flips, {20}] produces a list of twenty values of flip, something like this:
{2, 2, 0, 0, 3, 1, 0, 2, 1, 2, 2, 1, 2, 0, 3, 0, 0, 1, 1, 1}
This is then sorted: Sort @ Table[flips, {80}] resulting in
{0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3}
The Split operator breaks the above into runs of identical elements
{{0, 0, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 1}, {2, 2, 2, 2, 2, 2}, {3, 3}}
I then map the Length operator over the list of runs, resulting in tabulated counts:
{6, 6, 6, 2}
The use of @ and /@ for function application and mapping, respectively, is syntactic genius. It doesn't get much sweeter than that.
Wolfram recently started licensing Mathematica for home use at $300. It is a bargain at that price. The academic version costs even less, somewhere around $150. The academic and the home versions are functionally identical to the much more expensive commercial version. Grab a copy and you are armed to go do some Project Euler problems.
Posts