<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mathematica Cookbook</title>
	<atom:link href="http://mathematicacookbook.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://mathematicacookbook.com</link>
	<description>Building Blocks for Science, Engineering, Finance, Music and More</description>
	<lastBuildDate>Sat, 14 Apr 2012 02:25:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Challenge Answer</title>
		<link>http://mathematicacookbook.com/?p=270</link>
		<comments>http://mathematicacookbook.com/?p=270#comments</comments>
		<pubDate>Sat, 14 Apr 2012 01:54:57 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[DictionaryData]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=270</guid>
		<description><![CDATA[Here is the answer to the challenge in the previous post. First /@ Last[ SortBy[ GatherBy[{#, StringJoin[Sort[ToUpperCase[Characters[#]]]]} &#38; /@ DictionaryLookup[{"English", All}], Last], Length] ] The idea here is to extract every word from the English dictionary. Then we create pairs &#8230; <a href="http://mathematicacookbook.com/?p=270">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here is the answer to the challenge in the previous <a title="Challenge" href="http://mathematicacookbook.com/?p=265">post</a>.</p>
<pre>First /@
 Last[
  SortBy[
    GatherBy[{#, StringJoin[Sort[ToUpperCase[Characters[#]]]]} &amp;
        /@ DictionaryLookup[{"English", All}],
     Last],
    Length]
]</pre>
<p>The idea here is to extract every word from the English dictionary. Then we create pairs consisting of the initial word and the initial word with letters sorted and converted to uppercase. The idea is that the second entry is a anagram key &#8212; all words that are anagrams of each other will share the same key.</p>
<p>Then we use GatherBy to consolidate all the pairs with common keys and SortBy to order by the number of anagrams in the set. Finally Last is used to find the words that form the largest anagram set in the English dictionary and First to extract only the words (I drop the keys).</p>
<p>Here is some output that will make the steps clearer.</p>
<p>In[59]:= Take[SortBy[<br />
GatherBy[{#, StringJoin[Sort[ToUpperCase[Characters[#]]]]} &amp; /@<br />
DictionaryLookup[{"English", All}], Last], Length], -10]<br />
Out[59]= {{{&#8220;ales&#8221;, &#8220;AELS&#8221;}, {&#8220;Elsa&#8221;, &#8220;AELS&#8221;}, {&#8220;lase&#8221;, &#8220;AELS&#8221;}, {&#8220;leas&#8221;,<br />
&#8220;AELS&#8221;}, {&#8220;Lesa&#8221;, &#8220;AELS&#8221;}, {&#8220;sale&#8221;, &#8220;AELS&#8221;}, {&#8220;seal&#8221;, &#8220;AELS&#8221;}}, {{&#8220;capers&#8221;,<br />
&#8220;ACEPRS&#8221;}, {&#8220;crapes&#8221;, &#8220;ACEPRS&#8221;}, {&#8220;pacers&#8221;, &#8220;ACEPRS&#8221;}, {&#8220;parsec&#8221;,<br />
&#8220;ACEPRS&#8221;}, {&#8220;recaps&#8221;, &#8220;ACEPRS&#8221;}, {&#8220;scrape&#8221;, &#8220;ACEPRS&#8221;}, {&#8220;spacer&#8221;,<br />
&#8220;ACEPRS&#8221;}}, {{&#8220;carets&#8221;, &#8220;ACERST&#8221;}, {&#8220;caster&#8221;, &#8220;ACERST&#8221;}, {&#8220;caters&#8221;,<br />
&#8220;ACERST&#8221;}, {&#8220;crates&#8221;, &#8220;ACERST&#8221;}, {&#8220;reacts&#8221;, &#8220;ACERST&#8221;}, {&#8220;recast&#8221;,<br />
&#8220;ACERST&#8221;}, {&#8220;traces&#8221;, &#8220;ACERST&#8221;}}, {{&#8220;elan&#8221;, &#8220;AELN&#8221;}, {&#8220;lane&#8221;,<br />
&#8220;AELN&#8221;}, {&#8220;Lane&#8221;, &#8220;AELN&#8221;}, {&#8220;lean&#8221;, &#8220;AELN&#8221;}, {&#8220;Lean&#8221;, &#8220;AELN&#8221;}, {&#8220;Lena&#8221;,<br />
&#8220;AELN&#8221;}, {&#8220;Neal&#8221;, &#8220;AELN&#8221;}}, {{&#8220;Ingres&#8221;, &#8220;EGINRS&#8221;}, {&#8220;reigns&#8221;,<br />
&#8220;EGINRS&#8221;}, {&#8220;resign&#8221;, &#8220;EGINRS&#8221;}, {&#8220;sering&#8221;, &#8220;EGINRS&#8221;}, {&#8220;signer&#8221;,<br />
&#8220;EGINRS&#8221;}, {&#8220;singer&#8221;, &#8220;EGINRS&#8221;}, {&#8220;Singer&#8221;, &#8220;EGINRS&#8221;}}, {{&#8220;notes&#8221;,<br />
&#8220;ENOST&#8221;}, {&#8220;onset&#8221;, &#8220;ENOST&#8221;}, {&#8220;Seton&#8221;, &#8220;ENOST&#8221;}, {&#8220;steno&#8221;,<br />
&#8220;ENOST&#8221;}, {&#8220;stone&#8221;, &#8220;ENOST&#8221;}, {&#8220;Stone&#8221;, &#8220;ENOST&#8221;}, {&#8220;tones&#8221;,<br />
&#8220;ENOST&#8221;}}, {{&#8220;opts&#8221;, &#8220;OPST&#8221;}, {&#8220;post&#8221;, &#8220;OPST&#8221;}, {&#8220;Post&#8221;, &#8220;OPST&#8221;}, {&#8220;pots&#8221;,<br />
&#8220;OPST&#8221;}, {&#8220;spot&#8221;, &#8220;OPST&#8221;}, {&#8220;stop&#8221;, &#8220;OPST&#8221;}, {&#8220;tops&#8221;, &#8220;OPST&#8221;}}, {{&#8220;pares&#8221;,<br />
&#8220;AEPRS&#8221;}, {&#8220;parse&#8221;, &#8220;AEPRS&#8221;}, {&#8220;pears&#8221;, &#8220;AEPRS&#8221;}, {&#8220;rapes&#8221;,<br />
&#8220;AEPRS&#8221;}, {&#8220;reaps&#8221;, &#8220;AEPRS&#8221;}, {&#8220;spare&#8221;, &#8220;AEPRS&#8221;}, {&#8220;spear&#8221;,<br />
&#8220;AEPRS&#8221;}}, {{&#8220;ates&#8221;, &#8220;AEST&#8221;}, {&#8220;east&#8221;, &#8220;AEST&#8221;}, {&#8220;East&#8221;, &#8220;AEST&#8221;}, {&#8220;eats&#8221;,<br />
&#8220;AEST&#8221;}, {&#8220;etas&#8221;, &#8220;AEST&#8221;}, {&#8220;sate&#8221;, &#8220;AEST&#8221;}, {&#8220;seat&#8221;, &#8220;AEST&#8221;}, {&#8220;teas&#8221;,<br />
&#8220;AEST&#8221;}}, {{&#8220;least&#8221;, &#8220;AELST&#8221;}, {&#8220;slate&#8221;, &#8220;AELST&#8221;}, {&#8220;Stael&#8221;,<br />
&#8220;AELST&#8221;}, {&#8220;stale&#8221;, &#8220;AELST&#8221;}, {&#8220;steal&#8221;, &#8220;AELST&#8221;}, {&#8220;tales&#8221;,<br />
&#8220;AELST&#8221;}, {&#8220;teals&#8221;, &#8220;AELST&#8221;}, {&#8220;Tesla&#8221;, &#8220;AELST&#8221;}}}</p>
<p>The above shows the last 10 anagram families with the associated anagram key. The last one is the one used to generate the challenge output.</p>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=270</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Challenge</title>
		<link>http://mathematicacookbook.com/?p=265</link>
		<comments>http://mathematicacookbook.com/?p=265#comments</comments>
		<pubDate>Fri, 13 Apr 2012 03:25:50 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=265</guid>
		<description><![CDATA[I am going to do something different today. I am going to give you the output and ask you to come up with the Mathematica code that gives this output. Here it is: Out[1]= {"least", "slate", "Stael", "stale", "steal", "tales",  "teals", &#8230; <a href="http://mathematicacookbook.com/?p=265">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I am going to do something different today. I am going to give you the output and ask you to come up with the Mathematica code that gives this output. Here it is:</p>
<pre>Out[1]= {"least", "slate", "Stael", "stale", "steal", "tales", 
"teals", "Tesla"}</pre>
<p>The first question you need to answer is, what do these words have in common? This is pretty easy.</p>
<p>Next, what makes this particular set special?</p>
<p>Finally, what Mathematica code that output this set. Please no wise-guy answers like:</p>
<p>List["least", "slate", "Stael", "stale", "steal", "tales", "teals", "Tesla"]</p>
<p>The point is that this list can be computed from code that does not contain any of these words and the solution relates to the two questions asked above.</p>
<p>I&#8217;ll post the code in a few days if no one provides an answer.</p>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=265</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Binary Clock</title>
		<link>http://mathematicacookbook.com/?p=249</link>
		<comments>http://mathematicacookbook.com/?p=249#comments</comments>
		<pubDate>Sat, 28 Jan 2012 01:23:19 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=249</guid>
		<description><![CDATA[My friend Benny Pollak just got a new App into the App Store. It&#8217;s a Binary Clock. Simple App&#8217;s like this can are still quite a bit of work using Objective C. I took it upon myself to create the &#8230; <a href="http://mathematicacookbook.com/?p=249">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>My friend <a href="http://www.linkedin.com/pub/benny-pollak/7/a96/768" target="_blank">Benny Pollak</a> just got a <a href="http://itunes.apple.com/us/app/yaf-binary-clock/id495576659?mt=8" title="Binary Clock App" target="_blank">new App into the App Store</a>. It&#8217;s a Binary Clock. Simple App&#8217;s like this can are still quite a bit of work using Objective C. I took it upon myself to create the smallest program I could think of that implements a binary clock.</p>
<p><strong>Can you come up with a smaller one? Post it to my comments.</strong></p>
<pre>
Dynamic[Refresh[
  Transpose[
     IntegerDigits[#, 2, 4] &#038; /@
      Flatten[
       IntegerDigits[\[LeftFloor]#\[RightFloor], 10, 2] &#038; /@
        Date[][[4 ;; 6]]]] /. {0 -> \[EmptyCircle],
     1 -> \[FilledCircle]} // TableForm, UpdateInterval -> 1]]
</pre>
<p><script type="text/javascript">
    var cdf = new cdf_plugin(); 
    var defaultContent = '';
    if(defaultContent != "") {
        cdf.setDefaultContent(defaultContent);
    }
    cdf.embed("http://dl.dropbox.com/u/6875139/post249/BinaryClock.cdf", 400, 200);
</script>
</p>
<p><a href="http://dl.dropbox.com/u/6875139/post249/BinaryClockSrc.nb" title="Download Notebook">Download</a></p>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=249</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Angry Rationals. Part 3</title>
		<link>http://mathematicacookbook.com/?p=208</link>
		<comments>http://mathematicacookbook.com/?p=208#comments</comments>
		<pubDate>Tue, 24 Jan 2012 02:12:30 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Dynamic Interactivity]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Rule-Based Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=208</guid>
		<description><![CDATA[This is the third installment of our Angry Rationals game. I hope that even if you are not particularly interested in game programming this exercise helps you understand some of the more advanced things one can accomplish using Mathematica dynamic &#8230; <a href="http://mathematicacookbook.com/?p=208">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This is the third installment of our Angry Rationals game. I hope that even if you are not particularly interested in game programming this exercise helps you understand some of the more advanced things one can accomplish using Mathematica dynamic feature plus graphical abilities.</p>
<p>In <a title="Angry Rationals! A Lesson in Dynamic Interactivity and Iterative Development. Part 1" href="http://mathematicacookbook.com/?p=149">part 1</a> I defined the game structure and in <a title="Angry Rationals! A Lesson in Dynamic Interactivity and Iterative Development. Part 2" href="http://mathematicacookbook.com/?p=175">part 2</a> I added the first level but at this point the game is still very amateurish. Today&#8217;s goals are to:</p>
<ol>
<li>polish the look and feel of the game by adding more villans, backgrounds, and sound.</li>
<li>introduce a new level with more difficulty and more coding complexity</li>
<li>consider how the added complexity may call for different coding techniques</li>
</ol>
<p>Let&#8217;s start with the background image for the game. &nbsp;Working with images in notebooks is easy because you can just copy and paste the image and assign to a variable (Fig 1).</p>
<div id="attachment_210" class="wp-caption alignnone" style="width: 194px"><a href="http://mathematicacookbook.com/wp-content/uploads/2012/01/figbackground.jpg"><img class="size-full wp-image-210" title="figbackground" src="http://mathematicacookbook.com/wp-content/uploads/2012/01/figbackground.jpg" alt="Blackboard background" width="184" height="70" /></a><p class="wp-caption-text">Fig 1</p></div>
<p>The next step is getting the background into the game. This can be done using <em><strong>Inset</strong></em>. The inset image should be behind all graphics so we place it in the <em><strong>Prolog</strong></em> option of <strong>Graphics</strong> which cause it to be rendered before any other graphics object. &nbsp;Fig 2 shows how to do this. You should read the documentation for Inset for the details but basically you map a point on the image to a point on the graphic and specify a size for the resulting image.</p>
<div id="attachment_212" class="wp-caption alignnone" style="width: 436px"><a href="http://mathematicacookbook.com/wp-content/uploads/2012/01/fig2background.jpg"><img class="size-full wp-image-212" title="fig2background" src="http://mathematicacookbook.com/wp-content/uploads/2012/01/fig2background.jpg" alt="Inset image" width="426" height="333" /></a><p class="wp-caption-text">Fig 2</p></div>
<p>For sound, Mathematica provides a primitives <strong><em>Sound</em></strong>, <strong><em>SoundNote</em></strong>, and <strong><em>EmitSound</em></strong>. Again, I am not going to spend a lot of time explaining these now. There is a full chapter on Music and Sound in <a title="The Book" href="http://mathematicacookbook.com/?page_id=35">Mathematica Cookbook</a> written by a domain expert, <a title="John Kiehl" href="http://www.linkedin.com/pub/john-kiehl/4/bb7/744" target="_blank">John Kiehl</a>, but the Mathematica documentation is extensive as well. As a test I created a CDF that emits a sound when two objects collide.</p>
<div>
<pre style="color: #3366ff;">Manipulate[
 If[EuclideanDistance[p1, {0, 0}] &lt; 0.1,   Quiet@EmitSound[Sound[SoundNote["Snare"]]]];  Graphics[   {    Text[Style["x", 28], p1],    Text[Style["y", 28], {0.0, 0.0}]    },   PlotRange -&gt; {{-1, 1}, {-1, 1}}
  ]
 ,
 {p1, {-1, -1}, {1, 1}},
 SaveDefinitions -&gt; True
 ]</pre>
<p><script type="text/javascript">
    var cdf = new cdf_plugin(); 
    var defaultContent = '';
    if(defaultContent != "") {
        cdf.setDefaultContent(defaultContent);
    }
    cdf.embed("http://dl.dropbox.com/u/6875139/post208/fig3.cdf", 400, 400);
</script>
</p>
</div>
<p><strong>NOTE</strong>: The juxtaposition of <strong><em>Quiet</em></strong> and <strong>EmitSound</strong> above may look discordant but they do different things. <strong>Quiet</strong> suppresses any messages that may be generated by <strong>EmitSound</strong>.</p>
<p>Now that we have some of the preliminaries out of the way we can get back to the game. So far our game has been simple but even it is simplicity there is quite a few variables and logic for managing the game state. As we introduce more game elements it is clear this can quickly get out of hand so we need to take a step back and think like a software engineer.</p>
<p>The two techniques that tend to result in elegant Mathematica programs are Functional and Rule-Based programming. I will use both. My first goal is to encapsulate the state of the game&#8217;s villans (i.e. the irrationals). The state of a villan partly static (e.g. its name stays constant), partly dynamic in relation to the current state( e.g. a sound should be emitted just at the point of collision) and partly a function of prior states (e.g. once a villan is struck it should remain in the struck state). This implies a villan can be represented by a function that has memory of the past. Such a function is called a closure. But what should the function return? How about a set of rules that specify the present state of the villan. Let me describe what I mean step by step.</p>
<p>I want the present state of a villan to be a set of rules. For example:</p>
<pre style="color: #3366ff;">villan1 =
    {
        name-&gt;"π",
        hit -&gt; False,
        fontw -&gt; Bold,
        color -&gt;  Green,
        size -&gt; 32,
        pos -&gt; {0,1},
        transform -&gt; Identity,
        sound -&gt; Sound[SoundNote[None]]]
    }</pre>
<p>This states that currently villan1 has name π, has not be hit, is displaying as <strong>Bold</strong> and <strong>Green</strong> at a particular position and is neither transformed (e.g. not Rotated) nor emitting a sound. But this is the instantaneous representation of the villan. What we really want is to represent the villan as a function of the games state and history. The way to do that is to make the villan into a function (henceforth called the&nbsp;<strong><em>villan function</em></strong>).</p>
<pre style="color: #3366ff;">villan1 = Function[{projPos},
    {
        name-&gt;"pi",
        hit -&gt; collision[{0,1},projPos],
        fontw -&gt; Bold,
        color -&gt;  If[collision[{0,1},projPos],Pink,Green],
        size -&gt; 32,
        pos -&gt; {0,1},
        transform -&gt; If[collision[{0,1},projPos],
                           Rotate[#1,30 Degrees]&amp;,Identity]
        sound -&gt; If[collision[{0,1},projPos],
                       Sound[SoundNote["Snare"]],
                       Sound[SoundNote[None]]]
    }</pre>
<p>This now says that the rules for hit, color and transform and sound are a function of the projectiles position (i.e. a function of whether this particular villan is involved in a collision with the rational projectile).</p>
<p>But this is still not correct. Because, some of the rules are not simply a function of the projectile being hit but rather a function of <strong><em>ever being hit</em></strong>. That is to say, we need memory of the past. Now we can store this memory of the past externally and pass it in as another function argument but that complicates matters because now we need to maintain a bit of extra state for each villan separate from the villan. What we want is the villan itself to keep its own state. What we want is a <a title="Definition of a closure" href="http://http://en.wikipedia.org/wiki/Closure_(computer_science)" target="_blank">closure</a>. Now Mathematica does not explicitly provide closures but it is fairly easy to emulate them by taking advantage of the feature of <strong>Module</strong> that guarantees variables scoped within the <strong>Module</strong> are unique. We associate the module&#8217;s variables with the function by using a villan constructor (<strong><span style="color: #008000;">makeVillan</span></strong>). In addition, we use <strong>Options</strong> on the villan constructor to capture the default values. <span style="text-decoration: underline;">Keep in mind that <span style="color: #008000; text-decoration: underline;"><strong>makeVillan</strong></span> is distinct from the <span style="color: #008000; text-decoration: underline;">villan function</span> (its return value).&nbsp;</span></p>
<pre style="color: #3366ff;">Options[makeVillan] = {fontw -&gt; Bold, color -&gt; Green, size -&gt; IrrSZ};
makeVillan[aName_, aPos_, OptionsPattern[]] :=
 Module[{c1 = False},
  Function[{projPos, reset},
   With[{c2 = collision[aPos, projPos]},
    c1 = c1 || c2;
    c1 = If[reset, False, c1];
    {
     hit -&gt; c1,
     name -&gt; nm,
     fontw -&gt; OptionValue[fontw],
     color -&gt;  If[c1, Pink, OptionValue[color]],
     size -&gt; OptionValue[size],
     pos -&gt; aPos,
     transform -&gt; If[c1,
                        Rotate[#1, 30 Degree] &amp;,
                        Identity],
     sound -&gt; If[c2,
                    Sound[SoundNote["Snare"]]],
                    Sound[SoundNote[None]]]
     }
    ]
   ]
  ]</pre>
<p>This is relatively little code but it concentrates many Mathematica concepts so let&#8217;s review it line by line.</p>
<p><strong><span style="color: #008000;">Options[makeVillan] = {fontw -&gt; Bold, color -&gt; Green, size -&gt; IrrSZ};</span></strong><br />
This establish the defaults for a villan constructor. It says villans should be Bold and Green and have a size IrrSZ (which is a constant defined elsewhere.</p>
<p><strong><span style="color: #008000;">makeVillan[aName_, aPos_, OptionsPattern[]] :=</span></strong><br />
This says that to make a villan we provide a name and its position as well as additional options which can override the defaults.</p>
<p><span style="color: #008000;"><strong>Module[{c1 = False},</strong></span><br />
This says the makeVillan rule has a lexically scoped variable c1 whose initial value is False. This in itself is unremarkable except in relation to what comes next. For now, I'll say that c1 means "has this villan ever been involved in a collision".</p>
<p><strong><span style="color: #008000;">Function[{projPos, reset},</span></strong><br />
The value produced by makeVillan is a Function (i.e. we are returning a Function) and that function takes a projPos and another argument called reset (more on that later).</p>
<p><strong><span style="color: #008000;">With[{c2 = collision[aPos, projPos]},</span></strong><br />
Here we use With inside of the function to define a constant c2 which is a Boolean that states &#8220;is the villan currently hit&#8221;.</p>
<p><strong><span style="color: #008000;">c1 = c1 || c2;</span></strong><br />
<strong><span style="color: #008000;"> c1 = If[reset, False, c1];</span></strong><br />
These lines say, that it is true that the villan has been hit if it was hit before or is currently hit except if we are reseting its previous state of being hit. Being able to reset the state is important to starting a level over.</p>
<p><span style="color: #008000;">{</span><br />
<span style="color: #008000;"> hit -&gt; c1,</span><br />
<span style="color: #008000;"> name -&gt; nm,</span><br />
<span style="color: #008000;"> fontw -&gt; OptionValue[fontw],</span><br />
<span style="color: #008000;"> color -&gt; If[c1, Pink, OptionValue[color]],</span><br />
<span style="color: #008000;"> size -&gt; OptionValue[size],</span><br />
<span style="color: #008000;"> pos -&gt; aPos,</span><br />
<span style="color: #008000;"> transform -&gt; If[c1, Rotate[#1, 30 Degree] &amp;, Identity],</span><br />
<span style="color: #008000;"> sound -&gt; If[c2, Sound[SoundNote["Snare"]]],Sound[SoundNote[None]]]</span><br />
<span style="color: #008000;"> }</span><br />
These lines provide the return value of the villan function and as we alluded before, the value is a set of rules. But note that these rules reference the <strong>Module</strong> variable <span style="color: #008000;">c1</span>. But <span style="color: #008000;">c1</span>&#8216;s scope is not active during the invocation of the villan function;&nbsp;it is active only during the invocation of the constructor (<span style="color: #008000;">makeVillan</span>) hence we can see a bit of hanky-panky is going on here. What I am doing is stealing <span style="color: #008000;">c1</span> and relying on the fact that internally Mathematica has replaced <span style="color: #008000;">c1</span> with a name that is unique (see documentation for <strong>Module</strong> if this is unclear). Hence, our villan function acts as a closure over some unique global variable that has taken <span style="color: #008000;">c1</span>&#8216;s place (again, this is all under the covers). Since Mathematica guarantees the Kernel will have no other such variable, we are safe. In essence, we dynamically allocated a bit of storage for a villan function to remember the past. You should note that the rule for <span style="color: #008000;">sound</span> use <span style="color: #008000;">c2</span> rather than <span style="color: #008000;">c1</span> because a sound is only a function of the instaneous state of a collision not the past state.</p>
<p>I have introduced a lot of concepts but the payoff, as you will see, is that our next game level will be almost trivial to implement. In this level we will have 3 villans positioned along points of a Sine wave. The player will need to set the amplitude and frequency of the wave such that the rational projectile (3/4) collides will all 3 villans.</p>
<p>Below is the code for the new level. This includes the code that we explained above and the Manipulate for the actual game play. Note how the Manipulate is now devoid of game state management and control logic except for replacement rules and the controls. Most of the code in the Manipulate is simple option settings for the <strong>Graphics</strong> and the <strong>Manipulate</strong> itself.</p>
<pre style="color: #3366ff;">With[{COLLIDETHRS = 0.25, IrrSZ = 48},
 collision =
  Function[{p1, p2}, EuclideanDistance[p1, p2] &lt; COLLIDETHRS];
 villanCls = transform@Text[Style[name, fontw, color, size], pos];
 Options[makeVillan] = {fontw -&gt; Bold, color -&gt; Green,
   size -&gt; IrrSZ};
 makeVillan[nm_, p_, OptionsPattern[]] :=
  Module[{c1 = False},
   Function[{projPos, reset},
    With[{c2 = collision[p, projPos]},
     c1 = c1 || c2;
     c1 = If[reset, False, c1];
     {
      hit -&gt; c1,
      name -&gt; nm,
      fontw -&gt; OptionValue[fontw],
      color -&gt;  If[c1, Pink, OptionValue[color]],
      size -&gt; OptionValue[size],
      pos -&gt; p,
      transform -&gt; If[c1,
                         Rotate[#1, 30 Degree] &amp;,
                         Identity],
      sound -&gt; If[c2,
                     Quiet@EmitSound[Sound[SoundNote["Snare"]]]]
      }
     ]
    ]
   ]
 ]

With[{PiX1 = 2, PiY1 = 1.5, PiX2 = 10, PiY2 = 1.5, PiSZ = 28, EX1 = 6,
   EY1 = -1.5},
 villans = {makeVillan["\[Pi]", {PiX1, PiY1}],
    makeVillan["\[ExponentialE]", {EX1, EY1}],
    villan3 = makeVillan["\[Pi]", {PiX2, PiY2}] };
 ]

With[{TSTART = 0.2, TEND = 12.0},
 Manipulate[
  DynamicModule[{villans, pos, reset, path},
   reset = t &lt;= TSTART;
   pos = {t, f[t, p1, p2]};
   villans = {villan1[pos, reset], villan2[pos, reset],
     villan3[pos, reset]};
   sound /. villans;
   path = Table[{t, f[t, p1, p2]}, {t, TSTART, t, 0.1}];
   Graphics[
    {
     Line[path],
     Text[Style[3/4, Bold, Red, 24], pos],
     villanCls /. villans
     },
    Axes -&gt; True,
    PlotRange -&gt; {{0, 11}, {-3.5, 3.5}},
    PlotRangePadding -&gt; 0.35,
    ImagePadding -&gt; {{0, 0}, {0, 0}},
    Prolog -&gt; Inset[background, Center, Center, 13.0]]]

  ,
  {t, TSTART, TEND, Trigger},
  {p1, 0.0, 2.0},
  {p2, -1, 1},
  FrameLabel -&gt;  Style["p1 Sin[p2 t]", 18],
  TrackedSymbols :&gt; {t}
  ]
 ]</pre>
<p>Here is what the level looks like (this CDF has embedding issues. I am told this will improve in the next release of Mathematica)</p>
<div id="attachment_238" class="wp-caption alignnone" style="width: 417px"><a href="http://mathematicacookbook.com/wp-content/uploads/2012/01/AngryRationals32.jpg"><img class="size-full wp-image-238" title="AngryRationals3" src="http://mathematicacookbook.com/wp-content/uploads/2012/01/AngryRationals32.jpg" alt="Level 2 of Angry Rationals" width="407" height="408" /></a><p class="wp-caption-text">Fig 3</p></div>
<p><a title="Download CDF for Level 2 of Angry Rationals" href="http://dl.dropbox.com/u/6875139/post208/AngryRationals3.cdf">Download CDF</a></p>
<h2>Conclusion</h2>
<p>This installment covered a lot of ground but I hope gave you some food for thought. It is possible to create Manipulates that encompass a lot of logic without drowning in the logic as long as you think carefully how to encapsulate the logic by leveraging the best features of Mathematica. The techniques covered here are also discussed extensively in <a title="The Book" href="http://mathematicacookbook.com/?page_id=35">my book</a> (plus a lot more!).</p>
<p>This will be my last post on Angry Rationals for a while but I plan on continuing to work on the game as I have time and I will provide the final notebook for you to download to play and tweak when it is ready.</p>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=208</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Help Defeat SOPA</title>
		<link>http://mathematicacookbook.com/?p=204</link>
		<comments>http://mathematicacookbook.com/?p=204#comments</comments>
		<pubDate>Wed, 18 Jan 2012 02:44:49 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=204</guid>
		<description><![CDATA[See message from Tim O&#8217;Reilly. &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160;]]></description>
			<content:encoded><![CDATA[<div style="background-color: black; color: white;">
<p><strong>See message from</strong> <a title="Stop SOPA" href="http://oreilly.com/blackout.html?imm_mid=07c912&amp;cmp=em-orm-authors-sopa">Tim O&#8217;Reilly</a>.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=204</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Angry Rationals! A Lesson in Dynamic Interactivity and Iterative Development. Part 2</title>
		<link>http://mathematicacookbook.com/?p=175</link>
		<comments>http://mathematicacookbook.com/?p=175#comments</comments>
		<pubDate>Tue, 17 Jan 2012 01:46:36 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Dynamic Interactivity]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=175</guid>
		<description><![CDATA[In the first installment (Angry Rationals Part I) we set out the structure for a multi-level game inspired by Angry Birds. Today we will flesh things out a bit by adding some more compelling game play to our first level. &#8230; <a href="http://mathematicacookbook.com/?p=175">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In the first installment (<a title="Angry Rationals! A Lesson in Dynamic Interactivity and Iterative Development. Part 1" href="http://mathematicacookbook.com/?p=149">Angry Rationals Part I</a>) we set out the structure for a multi-level game inspired by Angry Birds. Today we will flesh things out a bit by adding some more compelling game play to our first level.</p>
<p>Level 1 of our game challenges  the player to set the initial position of a rational projectile (1/2) so its path along a parabola causes it to crash into the game&#8217;s first irrational villan (<strong>π</strong>). The level will have several effects:</p>
<ol>
<li>The projectile should leave a trace of its path as it flies across the screen.</li>
<li>If hit, the villan should change color to provide feedback to the player.</li>
<li>If hit, the villan should tip over to provide a degree of satisfaction to the player (and the rational).</li>
</ol>
<p>Additional effects, such as sound would be nice but we will save those for a future installment.</p>
<p>The first effect can be achieved using <em><strong>Line</strong></em> and <em><strong>Table</strong></em> to generate the points. The points come from the trigger variable <span style="color: #008000;"><em>t</em></span>, the single user set parameter <em><span style="color: #008000;">p1</span></em> and the function for a parabola <em><span style="color: #008000;">f[t_] := 1 &#8211; t^2</span></em>. Despite its name, Line can generate smooth curves provided the collection of points are finely spaced.</p>
<p><code style="color: #3366ff;"> f[t_] := 1 - t^2;<br />
path = Table[{t1 + p1, f[t1]}, {t1, TSTART + p1, t + p1, PathIncr}];<br />
</code></p>
<p>The second effect requires a means to detect collisions. <strong><em>EuclideanDistance</em></strong> does the trick as long as we define a collision as an intersection of two points within a reasonable delta.</p>
<p><code style="color: #3366ff;"> collision[p1_, p2_] := EuclideanDistance[p1, p2] &lt; COLLIDETHRS;<br />
</code></p>
<p>The game and sprites are implemented in terms of Mathematica&#8217;s 2D <strong><em>Graphics</em></strong> primitives. I already mentioned Line and I also use <strong><em>Text</em></strong> and <strong><em>Style</em></strong>. The third effect, tipping over the Pi is done using <strong>Rotate</strong>.</p>
<p>The remainder of the code is game state logic. In particular, when using <strong>Manipulate</strong>, remember that the body of the <strong>Manipulate</strong> is continuously being evaluated. This means that you must arrange for state variables to always represent the current state of play. For example, we have a state variable called success that is updated using the following logic.</p>
<p><code style="color: #3366ff;"><br />
success = success || collision[{t + p1, f[t]}, {PiX, PiY}];<br />
success = success &amp;&amp; t &gt; TSTART;<br />
</code></p>
<p>This keeps the value of success <strong>False</strong> until a collision is detected and then keeps the value of success <strong>True</strong> until the trigger variable <em><span style="color: #008000;">t</span></em> is reset to <em><span style="color: #008000;">TSTART</span></em>.</p>
<p>The complete code for level 1 follows.</p>
<pre style="color: #3366ff;">DynamicModule[{success = False},
 With[{LMARGIN = 50, RMARGIN = 50, BMARGIN = 50, TMARGIN = 50,
   TSTART = -1, TEND = 1, COLLIDETHRS = 0.05, PiX = 0.85, PiY = 0.35,
   PiSZ = 48, ratSZ = 28, PathIncr = 0.05, PlRngPad = 0.25,
   PlotRng = {{-1, 1}, {0, 1}}},
   Manipulate[
   DynamicModule[{f, pi, collision, path},
    f[t_] := 1 - t^2;
    path =
     Table[{t1 + p1, f[t1]}, {t1, TSTART + p1, t + p1, PathIncr}];
    collision[p1_, p2_] := EuclideanDistance[p1, p2] &lt; COLLIDETHRS;     success = success || collision[{t + p1, f[t]}, {PiX, PiY}];     success = success &amp;&amp; t &gt; TSTART;
    pi = If[success,
      Rotate[Text[
        Style[\[Pi], Bold, Pink, PiSZ], {PiX, PiY}], -30 Degree],
      Text[Style[\[Pi], Bold, Green, PiSZ], {PiX, PiY}]];

    Graphics[
     {
      Text[Style[1/2, Bold, Red, ratSZ], {t + p1, f[t]}],
      pi,
      Line[path]
      },
     PlotRange -&gt; PlotRng,
     PlotRangePadding -&gt; PlRngPad,
     ImagePadding -&gt; None]
    ],
   {p1, -0.1, 0.1},
   {t, TSTART, TEND, Trigger},
   FrameMargins -&gt; {{LMARGIN, RMARGIN}, {BMARGIN, TMARGIN}}
   ]]]</pre>
<p>Here is level 1 to try out by itself as a CDF. I needed to alter the structure because it seems Wolfram does not allow CDF&#8217;s containing <strong>DynamaicModule</strong> or <strong>With</strong>, which is a shame. This explains why Part 1 would not work.</p>
<p><script type="text/javascript">
    var cdf = new cdf_plugin(); 
    var defaultContent = '';
    if(defaultContent != "") {
        cdf.setDefaultContent(defaultContent);
    }
    cdf.embed("http://dl.dropbox.com/u/6875139/post175/AngryRationalsLevel1.nb", 500, 500);
</script>
</p>
<p>Lou can <a title="The Game so far" href="http://dl.dropbox.com/u/6875139/post175/AngryRationals02.cdf">download</a> the entire game, integrated into the framework from <a title="Angry Rationals! A Lesson in Dynamic Interactivity and Iterative Development. Part 1" href="http://mathematicacookbook.com/?p=149">Part 1</a>. In the next installment I&#8217;ll add more levels, sound and make the whole game it a bit more polished.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=175</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Angry Rationals! A Lesson in Dynamic Interactivity and Iterative Development. Part 1</title>
		<link>http://mathematicacookbook.com/?p=149</link>
		<comments>http://mathematicacookbook.com/?p=149#comments</comments>
		<pubDate>Mon, 16 Jan 2012 04:34:38 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Dynamic Interactivity]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=149</guid>
		<description><![CDATA[The Challenge Let&#8217;s create a game using Mathematica&#8217;s dynamic interactive features. Games are complex pieces of software so they present lots of opportunity to dig deep into Mathematica&#8217;s interactive features. However, this complexity also means we should GO SLOW and &#8230; <a href="http://mathematicacookbook.com/?p=149">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h2>The Challenge</h2>
<p>Let&#8217;s create a game using Mathematica&#8217;s dynamic interactive features. Games are complex pieces of software so they present lots of opportunity to dig deep into Mathematica&#8217;s interactive features. However, this complexity also means we should <strong>GO SLOW</strong> and build up the game in an iterative step-by-step fashion. In fact, it&#8217;s a good idea to build all complex pieces of Mathematica code this way. Therefore, I&#8217;ll break the blog up into several installments as I add functionality.</p>
<h2>The Game</h2>
<p><strong><span style="color: #ff0000;">Angry Rationals</span></strong> is inspired by the mega-hit, <a title="Angry Birds by Rovio" href="http://en.wikipedia.org/wiki/Angry_Birds" target="_blank">Angry Birds</a> (if you need to click on that link you may need to get out more!). Here is the games premise:</p>
<blockquote><p>The Rationals are ANGRY. Afterall, the rationals are the real work horses of the modern world. Engineers, mechanics and crafts-people of all kinds construct the objects of the world based on rulers that are ticked-off in rational divisions like 1/2, 3/4 and 7/8, etc. Did you ever hear a mechanic say, hey Bob, hand me a <a title="The Golden Ratio" href="http://mathworld.wolfram.com/GoldenRatio.html" target="_blank">Φ</a>-sized socket wrench? Of course, not! So, in addition to ticking off rulers the rationals are ticked-off at the irrationals (and especially those snooty <a title="aka, non-algebraic" href="http://mathworld.wolfram.com/TranscendentalNumber.html" target="_blank">transcendentals</a>) because the mathematicians give them too much attention! To make matters worse, the rationals, although infinite in quantity are out-numbered by their more numerous enemy (may a scourge be brought upon <a title="If you need to click this, you play games too much!" href="http://en.wikipedia.org/wiki/Georg_Cantor" target="_blank">Cantor&#8217;s</a> house)!</p>
<p>The object of the game is to help the rationals seek revenge by causing them to fly out and smash the irrationals into <a title="This dust is hard to clean up!" href="http://mathworld.wolfram.com/CantorDust.html" target="_blank">Cantor Dust</a> (metaphorically speaking). But unlike Angry Birds, you will use no sling shot but rather your mathematical wits to estimate the parameters of a function that govern the rationals trajectory so that they intersect with the irrationals and obliterate them!</p></blockquote>
<h2>Preliminaries</h2>
<p>Before reading further you should have a basic understanding of Mathematica&#8217;s dynamic features because I will not be spelling out every detail here. <a href="http://reference.wolfram.com/mathematica/tutorial/IntroductionToManipulate.html" target="_blank">Introduction to Manipulate</a>  and  <a href="http://reference.wolfram.com/mathematica/tutorial/IntroductionToDynamic.html" target="_blank">Introduction to Dynamic</a> are essential but you may want to read the advanced tutorials as well (<a href="http://reference.wolfram.com/mathematica/tutorial/AdvancedManipulateFunctionality.html" target="_blank">Advanced Manipulate</a> and <a href="http://reference.wolfram.com/mathematica/tutorial/AdvancedDynamicFunctionality.html" target="_blank">Dynamic</a>). Alternatively, you can read along and consult the documentation when you don&#8217;t understand something.</p>
<h2>Modest Beginnings</h2>
<p>As I already mentioned, the game is going to be built step by step so you won&#8217;t get to destroy any irrationals today! Instead, I am going to build a rough structure for the game to implement logic that allows a player to proceed through a set of increasingly difficult game levels. I&#8217;ll write this code in the first way that comes to mind but as the game increases in complexity it may need some refactoring.</p>
<p>First off, I use <em><strong><a href="http://reference.wolfram.com/mathematica/ref/PaneSelector.html" target="_blank">PaneSelector</a></strong></em> as the top most game controller. The goal here is to use a different pane for each level and transition between these levels via dynamic changes to the <span style="color: #008000;"><em>level</em></span> variable.</p>
<p><code style="color: #3366ff;"><br />
PaneSelector[{<br />
BYE -&gt; bye,<br />
LOST -&gt; lost,<br />
WON -&gt; won,<br />
1 -&gt; level1,<br />
LAST -&gt; last}, level]</code></p>
<p>For now, I&#8217;ll have only one &#8220;real&#8221; playing level (<em><span style="color: #008000;">1-&gt;level1</span></em>). <span style="color: #008000;"><em>BYE</em></span>, <span style="color: #008000;"><em>LOST</em></span> and <span style="color: #008000;"><em>WON</em></span> are constants that represent pseudo-levels for interacting with the player when they win, or lose a level and when they quit. The final level (<em><span style="color: #008000;">LAST-&gt;last</span></em>) will tell them that they have beaten the entire game.</p>
<p>The lowercase variables <em><span style="color: #008000;">bye</span></em>, <em><span style="color: #008000;">lost</span></em>, <span style="color: #008000;"><em>won</em></span>, <span style="color: #008000;"><em>level1</em></span> and <span style="color: #008000;"><em>last</em></span>  will evaluate to either <em><strong>DynamicModule</strong></em> or <em><strong>Manipulate</strong></em> as the requirements dictate. In general, I use <strong>DynamicModule+Dynamic</strong> when I need more flexibility than <strong>Manipulate</strong> provides.</p>
<p>Here is an example of a pseudo-level that gets activated when the player loses the current level of the game.</p>
<pre style="color: #3366ff;">lost =
     DynamicModule[{}, 
         Panel[
            Column[ {
               Graphics[{
                   Text[Style["You Lost!", Black, 20], {0, 0.8}],
                   Text[Style["Play Again?", Red, 20], {0, 0.5}]
                   },
                   PlotRange -&gt; {{-1, 1}, {0, 1}}],
               Row[{
                    Button["Yes", reset[savelevel]],
                    Button["No", level = -3]
                  }]
               },
               Alignment -&gt; Center
            ]
         ]
     ];</pre>
<p>Here the goal is to tell the user they lost and allow them to transition to the level they just were playing or to exit the game. Visually it looks like this:</p>
<p><img class="alignnone" title="User Lost" src="http://dl.dropbox.com/u/6875139/post149/lostlevel.gif" alt="Controls Displayed When User Loses a Level" width="198" height="142" /></p>
<p>Level 1 of the game is just a stub that we will develop further later. For now, the object of level 1 is simply to press a button before a counter reaches 1.0 (my boys told me this may win the lamest game of the year award). The counter is implemented using a <em><strong>Trigger</strong></em> . The game play starts when the trigger is activated. In the future, the dynamic trigger variable <span style="color: #008000;"><em>t</em></span> will drive the movement of the game sprites.</p>
<p>Here is the entire game structure that we will build upon in future installments. I wrap the whole structure in a <strong>Manipulate</strong>, since this is a requirement for publishing as a CDF. This outer <strong>Manipulate</strong> has a <em><span style="color: #008000;">dummy</span></em> variable with property None so it is not mapped to a controller. I also use options <em><span style="color: #008000;">Paneled-&gt;FALSE</span></em> and <em><span style="color: #008000;">AppearanceElements -&gt; None</span></em> to hide the visual elements and controls of the outer <strong>Manipulate</strong>. This is because I want all the interactions to live inside the <strong>PaneSelector</strong>. I use <em><strong>With</strong></em> to set up constants and <strong>DynamicModule</strong> to encapsulate the game state variables.</p>
<pre style="color: #3366ff;">Manipulate[
 With[{BYE = -3, LOST = -2, WON = -1, LAST=2, LMARGIN = 100, RMARGIN = 100,
   TMARGIN = 100, BMARGIN = 100, TSTART = -1.0, TEND = 1.0},
  DynamicModule[
   {success = False, savelevel = 1, bye, lost, won, level1, last,
    reset},
   reset[l_] := DynamicModule[{}, success = False; level = l];
   bye = Graphics[{Text[Style["Bye", Red, 24]]}];
   lost = DynamicModule[{},
     Panel[
      Column[
       {
        Graphics[
         {
          Text[Style["You Lost!", Black, 20], {0, 0.8}],
          Text[Style["Play Again?", Red, 20], {0, 0.5}]
          },
         PlotRange -&gt; {{-1, 1}, {0, 1}}],
        Row[{Button["Yes", reset[savelevel]],
          Button["No", reset[BYE]]}]
        },
       Alignment -&gt; Center
       ],
      FrameMargins -&gt; {{LMARGIN, RMARGIN}, {BMARGIN, TMARGIN}}
      ]
     ];
   (*Level1 - For now,
   the player need only press the button before t==1*)

   level1 = Manipulate[
     (*If user won, react immediatly *)

     If[success , level = savelevel + 1,
      (*Only evaluate failure when level is done (t&gt;=1)*)

      If[t &gt;= 1.0,
        savelevel = If[level &gt; 0, level, savelevel];
        level = LOST;
        ];
      ];
     (*Active game area for this level*)

     Row[{t, Button["Press", success = True,
        Enabled -&gt; (t &gt; -1.0)]}],
     {t, TSTART, TEND, Trigger},
     FrameMargins -&gt; {{LMARGIN, RMARGIN}, {BMARGIN, TMARGIN}}
     ];
   (*last - Getting last means you beat all levels*)
     last = DynamicModule[{},
     Dynamic[
      Panel[
       Column[
        {
         Graphics[
          {
           Text[Style["You Beat All Levels!", Black, 20], {0, 0.8}],
           Text[Style["Play Again?", Red, 20], {0, 0.5}]
           },
          PlotRange -&gt; {{-1, 1}, {0, 1}}],
         Row[{Button["Yes", reset[1]], Button["No", reset[BYE]]}]
         }, Alignment -&gt; Center
        ], FrameMargins -&gt; {{LMARGIN, RMARGIN}, {BMARGIN, TMARGIN}}
       ]]
     ];
   PaneSelector[{
     BYE -&gt; bye,
     LOST -&gt; lost,
     WON -&gt; won,
     1 -&gt; level1,
     LAST -&gt; last}, level]]
  ],
 {dummy, 0, 1, None},
 SaveDefinitions -&gt; True, Paneled -&gt; False,
 AppearanceElements -&gt; None, Deployed -&gt; True,
 Initialization :&gt; {level = 1}
 ]</pre>
<div style="border: 1px solid black;"><strong>NOTE</strong>: Try as a might I can&#8217;t get the code to work as a CDF embedded in the browser. It seems I am violating some rule Wolfram has for embeddable CDF&#8217;s. I&#8217;ll research that but in the mean time, if you have Mathematica you can <a href="http://dl.dropbox.com/u/6875139/post149/AngryRationals01.cdf">download the code</a> and try it yourself.</div>
<div style="border: 1px solid black;"><strong>UPDATE</strong>: <del datetime="2012-01-17T16:39:53+00:00">It seems that browser embedable CDF&#8217;s can&#8217;t use Block, DynamicModule, Module, or With inside the Manipulate. I am going to check with Wolfram to verify that is the case. It is not clear to me why these would be dangerous or difficult to support.</del></div>
<div style="border: 1px solid black;">UPDATE 2: Its not that simple! Testing this now!</div>
<p>In the next installment I will be adding some more compelling game logic to the first level (although impressing my hard-core gaming kids is gonna take some effort).</p>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=149</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Phi Video &#8211; Nice!</title>
		<link>http://mathematicacookbook.com/?p=145</link>
		<comments>http://mathematicacookbook.com/?p=145#comments</comments>
		<pubDate>Sat, 14 Jan 2012 22:02:35 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=145</guid>
		<description><![CDATA[Wonderful video on Phi and Fibonacci.]]></description>
			<content:encoded><![CDATA[<p><a title="The most irrational number: Phi" href="http://www.youtube.com/watch?v=lOIP_Z_-0Hs&amp;feature=youtu.be" target="_blank">Wonderful video on Phi and Fibonacci</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=145</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Constrained Random Number Generation</title>
		<link>http://mathematicacookbook.com/?p=119</link>
		<comments>http://mathematicacookbook.com/?p=119#comments</comments>
		<pubDate>Sat, 14 Jan 2012 02:52:00 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[Combinatorics]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Probability and Statistics]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=119</guid>
		<description><![CDATA[I was reading a thread on Math Forum that inspired todays post. The question was how to go about generating a set of pseudo-random numbers within a particular range that met some constraint. The obvious solution is to keep generating &#8230; <a href="http://mathematicacookbook.com/?p=119">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I was reading <a title="Mathematica: Applying rules to random integer generation" href="http://www.mymathforum.com/viewtopic.php?f=55&amp;t=23874" target="_blank">a thread on Math Forum</a> that inspired todays post.</p>
<p>The question was how to go about generating a set of pseudo-random numbers within a particular range that met some constraint. The obvious solution is to keep generating numbers in that range until the constraint is satisfied and that is where the thread ended. But this got me wondering if this is the best approach. Before diving into another possible approach let&#8217;s first explore the tools Mathematica provides for generating pseudo-randomness.</p>
<p><strong><em>RandomInteger</em></strong> and <strong><em>RandomReal</em></strong> are the most basic functions for random number generation. They can generate 1 or many numbers in specified range.<br />
<code><br />
<span style="color: #3366ff;"><br />
In[1]:= RandomInteger[{1, 30}]<br />
Out[1]= 23<br />
In[2]:= RandomInteger[{1, 30}, 5]<br />
Out[2]= {6, 1, 30, 6, 7}<br />
</span></code></p>
<p>Here I generate a single integer in the range {1,30} and then 5 integers in that range. One of the first constraints you might have in generating a set random numbers is that there be no repetitions. <strong>RandomInteger</strong> is not useful here because it provides no such guarantee. Calling <strong>RandomInteger</strong> repeatedly until there are no repetitions is way to brutish for anyone&#8217;s taste and certainly unnecessary because Mathematica provides the proper tools.</p>
<p><strong><em>RandomChoice</em></strong> and <strong><em>RandomSample</em></strong> are two functions that select random numbers from a set you provide. RandomSample will never sample an element of the set more than once, so for this application it is exactly what we need. You simple generate the <strong><em>Range</em></strong> of numbers you want and <strong>RandomSample</strong> does the rest.</p>
<p><code><br />
<span style="color: #3366ff;"><br />
In[3]:= RandomSample[Range[30], 5]<br />
Out[3]= {14, 22, 30, 29, 4}<br />
</span><br />
</code><br />
Given these tools we are close to solving the problem in the method suggested on Math Forum. All we need is a function that specifies the constraints. In the post the constraints were stated to be:</p>
<ol>
<li>5 integers in the Range[1,30]</li>
<li>At most 2 integers &lt;= 12</li>
<li>At least one integer &gt;=25</li>
<li>Each of the integers 3,4 and 7 can&#8217;t be a divisor for more than 3 of the random chosen integers</li>
<li>At most two consecutive integers.</li>
</ol>
<p>The first constraint is satisfied by simply using <strong>Range</strong>. The remainder can be tested using the following function. This function returns the list if the constraint is satisfied otherwise returns the empty list.<br />
<code><br />
<span style="color: #3366ff;"><br />
</span></code></p>
<p><code><span style="color: #3366ff;">constraint[l_List] := If[</span><br />
<span style="color: #3366ff;">   Count[l, x_Integer /; x &lt;= 12] &lt;= 2 &amp;&amp;</span><br />
<span style="color: #3366ff;">    Count[l, x_Integer /; x &gt;= 25] &gt;= 1 &amp;&amp;</span><br />
<span style="color: #3366ff;">    Count[l, x_Integer /; Or @@ Divisible[x, {3, 4, 7}]] &lt;= 3 &amp;&amp;</span><br />
<span style="color: #3366ff;">    Not[MatchQ[</span><br />
<span style="color: #3366ff;">      Sort[l], {___, x1_, y1_, ___, x2_, y2_, ___} /; </span><br />
<span style="color: #3366ff;">       x1 == y1 - 1 &amp;&amp; (x2 == y2 - 1 || y1 == x2 - 1)]], l, {}]</span></code></p>
<p>We can now generate random numbers that satisfy the constraint as follows.</p>
<p><code><span style="color: #3366ff;"><br />
In[5]:= Module[{s},<br />
While[Length[s = constraint[Evaluate[RandomSample[Range[30], 5]]]] == 0];s]<br />
Out[5]= {19, 27, 6, 13, 20}<br />
</span></code></p>
<p>This is basically the solution arrived at in Math Forum, except that solution uses Reap and Sow, (and seems to change the problem definition by the end of the post), but in spirit these solutions are the same.</p>
<p>What bothered me about this solution in general is that there could be many calls to RandomSample before the constraint is satisfied. To see how many, we can make a small modification.</p>
<p><code><br />
<span style="color: #3366ff;"><br />
In[6]:= Module[{s, n = 1},<br />
While[Length[s = constraint[Evaluate[RandomSample[Range[30], 5]]]] ==<br />
0, n++];<br />
{s, n}]<br />
Out[6]= {{2, 23, 29, 12, 22}, 2}</span></code></p>
<p>This code counts how many calls were made before the constraint was met and returns a list with the value and the count. This time we got lucky and met the constraint in 2 calls to <strong>RandomSample</strong>. Let&#8217;s wrap this in a table to see how we do over several calls.</p>
<p><code><span style="color: #3366ff;"> In[8]:= Table[<br />
Module[{s, n = 1},<br />
While[Length[<br />
s = constraint[Evaluate[RandomSample[Range[30], 5]]]] == 0,<br />
n++];<br />
{s, n}], {30}]<br />
Out[8]= {{{5, 20, 3, 29, 28}, 3}, {{30, 14, 21, 11, 13},<br />
7}, {{18, 1, 29, 22, 28}, 4}, {{25, 29, 12, 28, 6},<br />
1}, {{22, 14, 30, 18, 26}, 1}, {{12, 18, 13, 1, 30},<br />
2}, {{25, 4, 22, 18, 15}, 3}, {{26, 24, 9, 16, 19},<br />
2}, {{5, 20, 6, 26, 18}, 5}, {{16, 8, 22, 1, 30},<br />
6}, {{23, 22, 27, 13, 8}, 6}, {{25, 26, 30, 23, 12},<br />
3}, {{3, 6, 22, 25, 24}, 3}, {{15, 14, 29, 1, 26},<br />
3}, {{27, 24, 22, 7, 26}, 4}, {{2, 29, 26, 23, 19},<br />
1}, {{17, 23, 28, 5, 21}, 1}, {{6, 27, 20, 19, 17},<br />
1}, {{9, 29, 17, 19, 30}, 1}, {{29, 15, 25, 7, 27},<br />
3}, {{10, 28, 29, 27, 18}, 2}, {{28, 20, 17, 19, 26},<br />
1}, {{22, 28, 18, 21, 5}, 3}, {{5, 13, 7, 25, 24},<br />
1}, {{18, 10, 25, 30, 4}, 5}, {{1, 26, 12, 21, 17},<br />
3}, {{27, 22, 8, 26, 1}, 2}, {{28, 11, 26, 21, 10},<br />
1}, {{23, 24, 19, 27, 9}, 5}, {{27, 19, 20, 14, 22}, 4}}</span></code></p>
<p><code></code>Here you can see that it took up to 7 calls before RandomSample found a match. This is not that bad and for this problem it is probably a satisfactory solution. However, I tend to think in general terms when programming. In general terms, we could have a constraint that was very restrictive such that only a handful of values in the space we are sampling met the constraint. This would be bad because then <strong>RandomSample</strong> could be called many more times before in wandered onto a set that met the constraint.</p>
<p>After mulling over this for a day, another approach hit me. Why not generate every set that meets the constraint and then simply use <strong>RandomSample</strong> to select from that set. This solution has a potential problem of its own, in that the sample space might be huge! But let&#8217;s see how we do in this particular case.<code><span style="color: #3366ff;"><br />
</span></code></p>
<p><span style="color: #3366ff;">constraint[l_List] :=</span><br />
<span style="color: #3366ff;">  Count[l, x_Integer /; x &lt;= 12] &lt;= 2 &amp;&amp;</span><br />
<span style="color: #3366ff;">   Count[l, x_Integer /; x &gt;= 25] &gt;= 1 &amp;&amp;</span><br />
<span style="color: #3366ff;">   Count[l, x_Integer /; Or @@ Divisible[x, {3, 4, 7}]] &lt;= 3 &amp;&amp;</span><br />
<span style="color: #3366ff;">   Not[MatchQ[</span><br />
<span style="color: #3366ff;">     Sort[l], {___, x1_, y1_, ___, x2_, y2_, ___} /; </span><br />
<span style="color: #3366ff;">      x1 == y1 &#8211; 1 &amp;&amp; (x2 == y2 &#8211; 1 || y1 == x2 &#8211; 1)]]</span></p>
<p><span style="color: #3366ff;">In[19]:= sampleSpace = Select[Subsets[Range[30], {5}], constraint];</span><br />
<span style="color: #3366ff;"> Length[sampleSpace]</span><br />
<span style="color: #3366ff;"> Out[20]= 54047</span></p>
<p>It took a few seconds to complete, but we see that the sample space is a manageable 54047 elements. Note, I tweaked the constraint function to simply return <strong>True</strong> or <strong>False</strong> so using it with <strong>Select</strong> is easier. Here <strong>Subsets</strong> is used to generate all subsets of the integers 1-30 of exactly length 5 (that is what {5} means &#8211; the {} is important without the curly&#8217;s it will generate all subsets of 5 items or less).</p>
<p>Now that we captured <em>sampleSpace</em> we can simply use <strong>RandomChoice</strong> to generate as many sets as we need and be guaranteed that each answer will meet the constraint.</p>
<p><code><span style="color: #3366ff;"><br />
In[22]:= RandomChoice[sampleSpace, 25]<br />
Out[22]= {{11, 22, 24, 26, 28}, {2, 12, 19, 22, 30}, {2, 15, 19, 23,<br />
25}, {3, 4, 21, 26, 29}, {8, 14, 23, 26, 29}, {6, 18, 23, 28,<br />
29}, {8, 18, 19, 22, 26}, {2, 9, 23, 28, 29}, {9, 11, 16, 22,<br />
28}, {9, 13, 15, 22, 30}, {6, 8, 13, 16, 26}, {11, 13, 15, 27,<br />
28}, {2, 14, 18, 19, 27}, {2, 7, 26, 27, 30}, {3, 15, 17, 22,<br />
29}, {3, 5, 13, 16, 30}, {2, 5, 18, 19, 28}, {1, 7, 21, 22, 26}, {1,<br />
8, 18, 22, 26}, {10, 14, 16, 21, 26}, {3, 15, 21, 22, 29}, {2, 4,<br />
20, 23, 25}, {2, 13, 16, 19, 25}, {11, 16, 19, 20, 28}, {2, 6, 14,<br />
25, 26}}</span></code></p>
<h2>Conclusion</h2>
<p>Two viable solutions are presented to the problem of generating sets of random numbers subject to constraints. Which one is better depends on the particular parameters of your problem. For this particular problem, either is okay. For problems with a huge sample space, the first solution is better because finding a value should not take too many calls to <strong>RandomSample</strong>. For small sample spaces, the second technique is much better. This is a classic time/space trade-off and you&#8217;ll need to decide for yourself which technique suits the problem at hand.</p>
<p>Perhaps you have another approach? If so, I&#8217;d love to hear it!</p>
<p><a title="Mathematica Notebook" href="http://dl.dropbox.com/u/6875139/post119/constrainedRandomNumbers.nb">Download Notebook</a></p>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=119</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Functional Programming: Group Theory and Composition</title>
		<link>http://mathematicacookbook.com/?p=92</link>
		<comments>http://mathematicacookbook.com/?p=92#comments</comments>
		<pubDate>Wed, 11 Jan 2012 04:20:18 +0000</pubDate>
		<dc:creator>Sal Mangano</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://mathematicacookbook.com/?p=92</guid>
		<description><![CDATA[Group Theory has many important application in math and science. For instance, it provides a nice way to formalize the notion of symmetry. For example, an equilateral triangle {a,b,c} has 6 symmetries: i &#8211; identity v &#8211; rotation by 120 &#8230; <a href="http://mathematicacookbook.com/?p=92">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Group_(mathematics)" title="Wikipedia Entry for Group">Group Theory</a> has many important application in math and science. For instance, it provides a nice way to formalize the notion of symmetry. For example, an equilateral triangle <em>{a,b,c}</em> has 6 symmetries:</p>
<ol>
<li><strong>i</strong> &#8211; identity</li>
<li><strong>v</strong> &#8211; rotation by 120 degrees</li>
<li><strong>w</strong> &#8211; rotation by 240 degrees</li>
<li><strong>x</strong> &#8211; flipping about the axis defined by bisecting the angle at point <em>a</em></li>
<li><strong>y</strong> &#8211; flipping about the axis defined by bisecting the angle at point <em>b</em></li>
<li><strong>z</strong> &#8211; flipping about the axis defined by bisecting the angle at point <em>c</em></li>
</ol>
<p>We can implement these transformations as Mathematica functions on the points that define the triangle.</p>
<p>&nbsp;</p>
<p>Clear[a, b, c, i, v, w, x, y, z];</p>
<p>i[l : {p1_, p2_, p3_}] := l</p>
<p>v[l : {p1_, p2_, p3_}] := RotateRight[l, 1]</p>
<p>w[l : {p1_, p2_, p3_}] := RotateRight[l, 2]</p>
<p>x[{p1_, p2_, p3_}] := {p1, p3, p2}</p>
<p>y[{p1_, p2_, p3_}] := {p3, p2, p1}</p>
<p>z[{p1_, p2_, p3_}] := {p2, p1, p3}</p>
<p>Now we can visualize the behavior to verify these functions each result in an equilateral triangle of the same orientation.<br />
<code><br />
Clear[draw];<br />
draw[{a_, b_, c_}] :=<br />
Graphics[{Pink, Opacity[0.5], Polygon[{a, b, c}], Opacity[1], Black,<br />
Text[Style["A", Large, Bold], a], Text[Style["B", Large, Bold], b],<br />
Text[Style["C", Large, Bold], c]}, Frame -&gt; True, PlotRange -&gt; All]<br />
Manipulate[draw[f[eqtri]], {f, {i, v, w, x, y, z}}]<br />
</code><br />
<script type="text/javascript">
    var cdf = new cdf_plugin(); 
    var defaultContent = '';
    if(defaultContent != "") {
        cdf.setDefaultContent(defaultContent);
    }
    cdf.embed("http://dl.dropbox.com/u/6875139/post92/eqtrisym.cdf", 400, 400);
</script>
<br />
<a title="Download CDF" href="http://dl.dropbox.com/u/6875139/post92/eqtrisym.cdf">Download</a></p>
<p>Okay, that&#8217;s nice but what I really want to talk about now is the functional programming function known as <strong><strong>Composition</strong></strong>. In Chapter 2, Recipe 2.13 I discuss <strong>Composition</strong> and how it can be used with <strong>InverseFunction</strong>. Here I will discuss how it can be used to illustrate group theoretic concepts.</p>
<p>The 4 requirements of a mathematical group are:</p>
<ol>
<li>Closure</li>
<li>Associativity</li>
<li>Identity</li>
<li>Inverse</li>
</ol>
<h3>Closure</h3>
<p>Closure says that every composition of operations in the group must result in an operation that is in the group. We can test that the symetries of the equilateral triangle meet this criteria with the help of <strong>Composition</strong>.<br />
<code><br />
Module[{test = {a, b, c}, operations = {i, w, v, x, y, z}},<br />
 TableForm[Table[Composition[f1, f2][test],<br />
    {f1, operations},<br />
    {f2, operations}] /. {i[test] -> i, v[test] -> v, w[test] -> w,<br />
    x[test] -> x, y[test] -> y, z[test] -> z},<br />
  TableHeadings -> {operations, operations}]]<br />
</code><br />
<img src="http://dl.dropbox.com/u/6875139/post92/closure.gif" alt="The composition table of operations" /><br />
Here I use <strong><em>Table</em></strong> to generate every possible composition of the operations we defined on the equilateral triangle {a,b,c}. I then use <strong><em>ReplaceAll (/.)</em></strong> to substitute the result of these compositions with the name of the operation matching on the result of applying each function by itself. If the operations were not closed under composition then I would have at least one entry in the table that was not an operation in our set. This is not the case so I demonstrate the operations are indeed closed and in the process create a table that illustrates every composition.</p>
<h3>Associativity </h3>
<p>Associativity says that for every operation o1, o2, o3, (o1 . o2) . o3 = o1 . (o2 . o3) where . means composition. We can test that as well.<br />
<code><br />
In[29]:= Module[{test = {a, b, c}, operations = {i, w, v, x, y, z}},<br />
 And @@ Flatten[<br />
   Table[Composition[Composition[o1, o2], o3][test] ==<br />
     Composition[o1, Composition[o2, o3]][test],<br />
    {o1, operations},<br />
    {o2, operations},<br />
    {o3, operations}] ]]</p>
<p>Out[29]= True<br />
</code><br />
This code uses <strong>Table</strong> to construct every possible composition of three operations by composing o1 and o2 first and then composing the result with o3 and verifying that is the same as composing o1 with the composition of o2 and o3. By <strong>And</strong>ing the results together we verify that each comparison evaluated to <strong>True</strong>.</p>
<h3>Identity and Inverse</h3>
<p>We included an identity operation <em>i</em> so there is nothing to verify there. Groups also require that every operation has an inverse. This means that o . Inverse[o] == i for every o. We can see that is the case by inspecting the table of compositions and verifying in that each column and each row has one and only one i. This confirms that an inverse exists and it is unique for every o.</p>
<h2>Conclusion</h2>
<p>When I first encountered Composition in Mathematica, I did not know what to make of it. It seemed to be of only theoretical utility. But, again and again I find neat applications. In fact, <strong>Composition</strong> was an integral element in my entry in the <a href="http://blog.wolfram.com/2010/12/17/the-mathematica-one-liner-competition/" title="My One Liner">2010 Mathematica one-liner competition</a>. If you are interested in learning Group Theory you might try the above exercise on other groups. You can find some <a href="http://en.wikipedia.org/wiki/Examples_of_groups" title="Example Groups from Wikipedia">here</a>, <a href="http://planetmath.org/encyclopedia/ExamplesOfGroups.html" title="Planet Math Groups">here</a> or <a href="http://mathworld.wolfram.com/FiniteGroup.html" title="Wolfram Math World - Finite Groups">here</a>. You probably want to stick with the finite ones!</p>
<p><a href="http://dl.dropbox.com/u/6875139/post92/groups.nb" title="Download notebook">Get the notebook code</a></p>
]]></content:encoded>
			<wfw:commentRss>http://mathematicacookbook.com/?feed=rss2&#038;p=92</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

