<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>popcyclical</title>
    <link>http://popcyclical.com/</link>
    <description>The software development blog of Jim "poprhythm" Kolpack</description>
    <language>en-us</language>
    <copyright>Jim Kolpack</copyright>
    <lastBuildDate>Mon, 19 Aug 2013 00:42:53 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.12105.0</generator>
    <managingEditor>dasblog@example.com</managingEditor>
    <webMaster>dasblog@example.com</webMaster>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=3f2ff69b-f958-4faa-8337-9e2222537430</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,3f2ff69b-f958-4faa-8337-9e2222537430.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,3f2ff69b-f958-4faa-8337-9e2222537430.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=3f2ff69b-f958-4faa-8337-9e2222537430</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <img title="Traveling Salesman Problem Excerpt" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin-left: auto; display: block; padding-right: 0px; border-top-width: 0px; margin-right: auto" border="0" alt="Traveling Salesman Problem Excerpt" src="http://popcyclical.com/content/binary/Windows-Live-Writer/Traveling-Salesman-Problem-Visualization_11F14/Untitled-2_3.jpg" width="1085" height="163" />
        </p>
        <p>
Over the last 9 weeks I've had the pleasure of being enrolled in the <a href="http://www.coursera.org/course/optimization">Discrete
Optimization</a> course at <a href="http://www.coursera.org">Coursera</a> taught by <a href="https://www.coursera.org/instructor/~256">Pascal
Van Hentenryck</a>. I had previously taken several of other massive open online courses
(MOOCs), but this was the most challenging and rewarding. The key ingredients of this
course were the unquestionable enthusiasm by its instructor and assistants, who created
an excellent series of lectures and were personally involved at every step, as well
as a game-like grading system, where the better your algorithm, the better your grade.
It was rather intense! None of the programming assignments are issued with a well-defined
strategy for creating a solution. Instead, the lectures cover various types of techniques
and tools to be implemented and tinkered with by the students. Another interesting
feature of the course is that all of the lectures and assignments are available from
the first day. Most courses impose a schedule of lectures and assignments to be watched
and completed on a week-by-week basis. The open structure of Discrete Optimization
had me feeling a bit bewildered at first. They do provide a suggested study plan,
so I (mostly) stuck with that and was able to make steady progress throughout the
course.
</p>
        <p>
One of the topics that resonated with many of the students, myself included, was that
of <a href="http://en.wikipedia.org/wiki/Local_search_(optimization)">Local Search</a>.
It's an idea that's easy to conceptualize and program, yet very powerful. I implemented
a Local Search solution for the Traveling Salesmen Problem and, along the way, added
some code to visualize some of the larger solutions. It looked pretty cool to see
so many points connected together by a continuous route. I began experimenting with
animating the algorithm as it finds a solution. Later, the professor's assistant (AKA
graciously-answering-forum-questions-<a href="http://www.coffr.in/">Carleton Coffrin</a>)
put out a call for the students to create visualizations of various heuristics that
can be used to solve TSP. Here is my contribution – it displays <a href="http://en.wikipedia.org/wiki/Greedy_algorithm">Greedy
algorithm</a>, <a href="http://en.wikipedia.org/wiki/Local_search_(optimization)">Local
Search</a>, and <a href="http://en.wikipedia.org/wiki/Simulated_annealing">Simulated
annealing</a> strategies for a group of US cities.
</p>
        <div id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:95f87d4e-3c01-4df7-9021-8eca0c214800" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px">
          <div>
            <object width="490" height="274">
              <param name="movie" value="//www.youtube.com/v/SC5CX8drAtU?hl=en_US&amp;version=3&amp;rel=0" />
              <param name="allowFullScreen" value="true" />
              <param name="allowscriptaccess" value="always" />
              <embed src="//www.youtube.com/v/SC5CX8drAtU?hl=en_US&amp;version=3&amp;rel=0" type="application/x-shockwave-flash" width="490" height="274" allowscriptaccess="always" allowfullscreen="true">
              </embed>
            </object>
          </div>
          <div style="width:490px;clear:both;font-size:.8em">Traveling Salesman Problem Visualization
</div>
        </div>
        <hr />
        <p>
I’ve seen some interest in knowing how this was created. Here are the steps:
</p>
        <ul>
          <li>
I wanted to use some "real" map data to help illustrate the problem.  From a
list of cities from <a href="http://www.geonames.org/export/">geonames.org</a>, filtered
by country and population to generate data sets 
</li>
          <li>
Ran these through my TSP solver from the Discrete Optimization course assignment,
collecting the intermediate routes as improvements are made 
</li>
          <li>
Generated a metric ton of still images to illustrate the transitions between the routes
- this involves: 
</li>
          <ul>
            <li>
translating the points and lines onto a bitmap 
</li>
            <li>
"tweening" many frames between each route to provide smooth transitions. I tried several
different "easing functions" but ended up with something like "easeInOutQuad" shown
on this <a href="http://easings.net/">Easing Functions</a> page 
</li>
            <li>
… also generate images for the distance and temperature 
</li>
          </ul>
          <li>
Imported these as numbered frames into Adobe Premiere Elements - I don't use anything
fancy, just the text, some cross-dissolve transitions, and alter the speed of the
frames - the same could likely be done with open source editors ( <a href="http://www.videolan.org/vlmc/">VLMC</a>?) 
</li>
          <li>
The map of the US is a "flat" Mercator projection so that the latitude and longitude
coordinates from the city list will show up in approximately the correct location
- it's from here: <a href="http://commons.wikimedia.org/wiki/File:Mercator_Projection.svg">Mercator
Projection.svg</a></li>
          <li>
... and then a bunch of slicing and dicing and mixing and matching inside the video
editor to "tell the story"</li>
        </ul>
        <p>
The code was done in .NET – here’s some pseudo-code used to generate the animation:
</p>
        <pre>
          <code>minX, minY = points.Minimum(X), points.Minimum(Y) maxX, maxY = points.Maximum(X),
points.Maximum(Y) w = maxX - minX h = maxY - minY imgW = 720 imgH = 480 frame = 0
foreach routePair in routes.Pairwise() edgePairs = CalculateEdgePairs(routePair.Current,
route.Next) for tween in [0..30] tweenFactor = EaseInOut(tween) using (var bitmap
= new Bitmap(imgW, imgH)) using (var g = Graphics.FromImage(bitmap)) RenderPoints(g,
points, brush); RenderEdges(g, edgePairs, tweenFactor, pen); bitmap.Save(filename
+ frame++, ImageFormat.Png); RenderPoints(g, points, brush) foreach (var p in points)
point = Translate(p); g.FillEllipse(brush, point.X, point.Y, _pointSize); RenderEdges(g,
edgePairs, tweenFactor, pen) // interpolate the edge changes foreach (var edgePair
in edgePairs) point1Current = Translate(points[edgePair.Current.Point1]); point1Next
= Translate(points[edgePair.Next.Point1]); point2Current = Translate(points[edgePair.Current.Point2]);
point2Next = Translate(points[edgePair.Next.Point2]); g.DrawLine(pen, (point1Next.X
- point1Current.X)*tweenFactor + point1Current.X, (point1Next.Y - point1Current.Y)*tweenFactor
+ point1Current.Y, (point2Next.X - point2Current.X)*tweenFactor + point2Current.X,
(point2Next.Y - point2Current.Y)*tweenFactor + point2Current.Y); Translate(point)
new Point( X = (point.X - minX) / w * _imgW, Y = (point.Y - minY) / h * _imgH) EaseInOut(x)
(x*x)/(x*x + (1 - x)*(1 - x))</code>
        </pre>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=3f2ff69b-f958-4faa-8337-9e2222537430" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>Traveling Salesman Problem Visualization</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,3f2ff69b-f958-4faa-8337-9e2222537430.aspx</guid>
      <link>http://popcyclical.com/2013/08/19/TravelingSalesmanProblemVisualization.aspx</link>
      <pubDate>Mon, 19 Aug 2013 00:42:53 GMT</pubDate>
      <description>&lt;p&gt;
&lt;img title="Traveling Salesman Problem Excerpt" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin-left: auto; display: block; padding-right: 0px; border-top-width: 0px; margin-right: auto" border="0" alt="Traveling Salesman Problem Excerpt" src="http://popcyclical.com/content/binary/Windows-Live-Writer/Traveling-Salesman-Problem-Visualization_11F14/Untitled-2_3.jpg" width="1085" height="163"&gt;
&lt;/p&gt;
&lt;p&gt;
Over the last 9 weeks I've had the pleasure of being enrolled in the &lt;a href="http://www.coursera.org/course/optimization"&gt;Discrete
Optimization&lt;/a&gt; course at &lt;a href="http://www.coursera.org"&gt;Coursera&lt;/a&gt; taught by &lt;a href="https://www.coursera.org/instructor/~256"&gt;Pascal
Van Hentenryck&lt;/a&gt;. I had previously taken several of other massive open online courses
(MOOCs), but this was the most challenging and rewarding. The key ingredients of this
course were the unquestionable enthusiasm by its instructor and assistants, who created
an excellent series of lectures and were personally involved at every step, as well
as a game-like grading system, where the better your algorithm, the better your grade.
It was rather intense! None of the programming assignments are issued with a well-defined
strategy for creating a solution. Instead, the lectures cover various types of techniques
and tools to be implemented and tinkered with by the students. Another interesting
feature of the course is that all of the lectures and assignments are available from
the first day. Most courses impose a schedule of lectures and assignments to be watched
and completed on a week-by-week basis. The open structure of Discrete Optimization
had me feeling a bit bewildered at first. They do provide a suggested study plan,
so I (mostly) stuck with that and was able to make steady progress throughout the
course.
&lt;/p&gt;
&lt;p&gt;
One of the topics that resonated with many of the students, myself included, was that
of &lt;a href="http://en.wikipedia.org/wiki/Local_search_(optimization)"&gt;Local Search&lt;/a&gt;.
It's an idea that's easy to conceptualize and program, yet very powerful. I implemented
a Local Search solution for the Traveling Salesmen Problem and, along the way, added
some code to visualize some of the larger solutions. It looked pretty cool to see
so many points connected together by a continuous route. I began experimenting with
animating the algorithm as it finds a solution. Later, the professor's assistant (AKA
graciously-answering-forum-questions-&lt;a href="http://www.coffr.in/"&gt;Carleton Coffrin&lt;/a&gt;)
put out a call for the students to create visualizations of various heuristics that
can be used to solve TSP. Here is my contribution – it displays &lt;a href="http://en.wikipedia.org/wiki/Greedy_algorithm"&gt;Greedy
algorithm&lt;/a&gt;, &lt;a href="http://en.wikipedia.org/wiki/Local_search_(optimization)"&gt;Local
Search&lt;/a&gt;, and &lt;a href="http://en.wikipedia.org/wiki/Simulated_annealing"&gt;Simulated
annealing&lt;/a&gt; strategies for a group of US cities.
&lt;/p&gt;
&lt;div id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:95f87d4e-3c01-4df7-9021-8eca0c214800" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;
&lt;div&gt;
&lt;object width="490" height="274"&gt;
&lt;param name="movie" value="//www.youtube.com/v/SC5CX8drAtU?hl=en_US&amp;amp;version=3&amp;amp;rel=0"&gt;&gt;
&lt;param name="allowFullScreen" value="true"&gt;&gt;
&lt;param name="allowscriptaccess" value="always"&gt;&gt;&lt;embed src="//www.youtube.com/v/SC5CX8drAtU?hl=en_US&amp;amp;version=3&amp;amp;rel=0" type="application/x-shockwave-flash" width="490" height="274" allowscriptaccess="always" allowfullscreen="true"&gt;&lt;/embed&gt;
&lt;/object&gt;
&lt;/div&gt;
&lt;div style="width:490px;clear:both;font-size:.8em"&gt;Traveling Salesman Problem Visualization
&lt;/div&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;p&gt;
I’ve seen some interest in knowing how this was created. Here are the steps:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
I wanted to use some "real" map data to help illustrate the problem.&amp;nbsp; From a
list of cities from &lt;a href="http://www.geonames.org/export/"&gt;geonames.org&lt;/a&gt;, filtered
by country and population to generate data sets 
&lt;li&gt;
Ran these through my TSP solver from the Discrete Optimization course assignment,
collecting the intermediate routes as improvements are made 
&lt;li&gt;
Generated a metric ton of still images to illustrate the transitions between the routes
- this involves: 
&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;
translating the points and lines onto a bitmap 
&lt;li&gt;
"tweening" many frames between each route to provide smooth transitions. I tried several
different "easing functions" but ended up with something like "easeInOutQuad" shown
on this &lt;a href="http://easings.net/"&gt;Easing Functions&lt;/a&gt; page 
&lt;/li&gt;
&lt;li&gt;
… also generate images for the distance and temperature 
&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;
Imported these as numbered frames into Adobe Premiere Elements - I don't use anything
fancy, just the text, some cross-dissolve transitions, and alter the speed of the
frames - the same could likely be done with open source editors ( &lt;a href="http://www.videolan.org/vlmc/"&gt;VLMC&lt;/a&gt;?) 
&lt;li&gt;
The map of the US is a "flat" Mercator projection so that the latitude and longitude
coordinates from the city list will show up in approximately the correct location
- it's from here: &lt;a href="http://commons.wikimedia.org/wiki/File:Mercator_Projection.svg"&gt;Mercator
Projection.svg&lt;/a&gt; 
&lt;li&gt;
... and then a bunch of slicing and dicing and mixing and matching inside the video
editor to "tell the story"&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
The code was done in .NET – here’s some pseudo-code used to generate the animation:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;minX, minY = points.Minimum(X), points.Minimum(Y) maxX, maxY = points.Maximum(X),
points.Maximum(Y) w = maxX - minX h = maxY - minY imgW = 720 imgH = 480 frame = 0
foreach routePair in routes.Pairwise() edgePairs = CalculateEdgePairs(routePair.Current,
route.Next) for tween in [0..30] tweenFactor = EaseInOut(tween) using (var bitmap
= new Bitmap(imgW, imgH)) using (var g = Graphics.FromImage(bitmap)) RenderPoints(g,
points, brush); RenderEdges(g, edgePairs, tweenFactor, pen); bitmap.Save(filename
+ frame++, ImageFormat.Png); RenderPoints(g, points, brush) foreach (var p in points)
point = Translate(p); g.FillEllipse(brush, point.X, point.Y, _pointSize); RenderEdges(g,
edgePairs, tweenFactor, pen) // interpolate the edge changes foreach (var edgePair
in edgePairs) point1Current = Translate(points[edgePair.Current.Point1]); point1Next
= Translate(points[edgePair.Next.Point1]); point2Current = Translate(points[edgePair.Current.Point2]);
point2Next = Translate(points[edgePair.Next.Point2]); g.DrawLine(pen, (point1Next.X
- point1Current.X)*tweenFactor + point1Current.X, (point1Next.Y - point1Current.Y)*tweenFactor
+ point1Current.Y, (point2Next.X - point2Current.X)*tweenFactor + point2Current.X,
(point2Next.Y - point2Current.Y)*tweenFactor + point2Current.Y); Translate(point)
new Point( X = (point.X - minX) / w * _imgW, Y = (point.Y - minY) / h * _imgH) EaseInOut(x)
(x*x)/(x*x + (1 - x)*(1 - x))&lt;/code&gt;&lt;/pre&gt;&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=3f2ff69b-f958-4faa-8337-9e2222537430" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,3f2ff69b-f958-4faa-8337-9e2222537430.aspx</comments>
      <category>algorithms</category>
      <category>visualization</category>
    </item>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=bafb3f1f-fed2-48f2-94b8-e5a2a8651044</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,bafb3f1f-fed2-48f2-94b8-e5a2a8651044.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,bafb3f1f-fed2-48f2-94b8-e5a2a8651044.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=bafb3f1f-fed2-48f2-94b8-e5a2a8651044</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <img style="display: inline" title="rainbowspirograph" alt="rainbowspirograph" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/rainbowspirograph.png" width="956" height="144" />
        <p>
So intense. We've heard how HTML5's canvas element will provide device-independent
in-browser graphics – and now I want a taste! After seeing some <a href="http://www.spielzeugz.de/html5/liquid-particles.html">magnificent</a><a href="http://peterned.home.xs4all.nl/demooo/">demos</a>,
I started wondering what the plumbing looks like.  I haven't touched any graphical
code since maybe 1994 in <a href="http://en.wikipedia.org/wiki/QBASIC">QBasic</a>,
so come along with me as I learn.
</p>
        <p>
Also, I'm giving <a href="http://coffeescript.org/">CoffeeScript</a> a spin. I saw
a presentation by <a href="https://twitter.com/#!/dmohl">Daniel Mohl</a> at <a href="http://codestock.org/">Codestock</a> a
few weeks ago and thought it was fantastic. You write in a terse-clean-"modern" language
and get the functionally equivalent JavaScript out the other end.  So long to
writing <code>function(){...}</code> every three lines! Much of the syntax is based
on Ruby, so it's an easy language to read - I'll comment on any syntax that isn't
immediately obvious.
</p>
        <p>
But the important question is - what to draw?  I follow a few graphic design
blogs and remember seeing some neat <a href="http://veerle.duoh.com/design/article/illustrator_full_spectrum_spirograph">geometric
patterns</a> on <a href="http://veerle.duoh.com">veerle's blog</a> done in Adobe Illustrator.
These were inspired by the kaleidoscopic artwork of <a href="http://crowquills.com/">Andy
Gilmore</a> – check them out, some of the pieces are kind of hypnotic. The specific
creation that motivated Veerle's tutorial can be <a href="http://crowquills.com/1061691/06-30-2008">seen
here</a>. It has a beautiful simplicity. As Veerle mentions - we don't want to make
an exact replica, but instead use some of the patterns as a starting point of something
original.<img style="background-image: none; border-right-width: 0px; margin: 10px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="HTML5 arc" border="0" alt="HTML5 arc" align="right" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/arc_3.png" width="304" height="304" /></p>
        <p>
The absolute first step is to draw a circle, just like it was in the Illustrator tutorial
by Veerle. Well, part of a circle. I found it easiest to get the desired results using
an "arc".  This is a term that simply means "a specific section along the side
of the circle".  What this entails for the HTML5 canvas is specifying the center
point of the circle, the radius, and the angles at the start and end the arc. 
My trigonometry knowledge has deteriorated over the years (if it ever existed to begin
with) – but this is pretty simple. The right-most point on the circle has an angle
of 0π, travelling clockwise to the bottom-most point is .5π, the left-most has 1π,
up to the top at 1.5π, and a full circle is (of course) 2π.  To draw a full circle,
you'd type in <code>context.arc(0,0,radius,0,Math.PI * 2)</code>.  <em>Note:
the angles I learned in school were oriented counterclockwise, yet most of the examples
I've seen for HTML5 canvas are clockwise – most likely because the y-axis increases
in a downward direction instead of up.  I'll keep it clockwise here.</em></p>
        <h3>Access the HTML5 Canvas using CoffeeScript
</h3>
        <p>
But what's this context, you ask? I might have lied about the first step – the super-absolute
first step will be to set up the HTML5 canvas object so that we can draw on it. 
Here's a complete example of a using CoffeeScript in a script tag with the in-browser
compiler to accomplish this.
</p>
        <pre>
          <code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Full on rainbow
Spirograph&lt;/title&gt; &lt;script src="scripts/jquery-1.7.2.min.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/coffeescript"&gt; canvasSize = 300 # shortcut for jquery's document
ready jQuery -&gt; # get the canvas element (using jquery) canvas = $('#myCanvas')[0]
# set the width and height of the canvas element canvas.width = canvas.height = canvasSize
# get the API object for drawing on the canvas ctx = canvas.getContext '2d' # make
a dark background ctx.fillStyle = '#002b36' ctx.fillRect(0,0,canvasSize,canvasSize)
# write some text ctx.font = '30px Arial' ctx.fillStyle = 'white' ctx.fillText("#myCanvas",
80, 150) &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id="myCanvas"&gt;&lt;/canvas&gt;
&lt;/body&gt; &lt;!-- download in-browser coffee-script compiler at --&gt; &lt;!--
https://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js --&gt;
&lt;!-- coffee-script.js goes AFTER all the CoffeeScript. --&gt; &lt;script type="text/javascript"
src="scripts/coffee-script.js"&gt;&lt;/script&gt; &lt;/html&gt;</code>
        </pre>
        <img style="background-image: none; border-right-width: 0px; margin: 10px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="HTML5 canvas example" border="0" alt="HTML5 canvas example" align="right" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/canvas_1.png" width="244" height="298" />
        <p>
This generates a page containing a dark 300x300 rectangle with "#myCanvas" written
in white. This is great for kicking the tires, but the script is getting compiled
down to JavaScript each time the page loads.  It's preferable to compile it ahead
of time.  With a little tooling this process becomes nearly transparent. 
In Visual Studio a great option is the <a href="http://www.mindscapehq.com/products/web-workbench">Web
Workbench extension by Mindscape</a>.  It automatically compiles your CoffeeScript
(and <a href="http://sass-lang.com/">Sass</a> and <a href="http://lesscss.org/">LESS</a>)
scripts each time the file is saved. After making this change, the code now looks
like...
</p>
        <pre style="border-bottom: #002b36 1px solid">
          <code>&lt;!DOCTYPE html&gt; &lt;html&gt;
&lt;head&gt; &lt;title&gt;Full on rainbow Spirograph&lt;/title&gt; &lt;script src="scripts/jquery-1.7.2.min.js"
type="text/javascript"&gt;&lt;/script&gt; &lt;script src="scripts/CoffeeScript_Compiled.js"
type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id="myCanvas"&gt;&lt;/canvas&gt;
&lt;/body&gt; &lt;/html&gt;</code>
        </pre>
        <div style="width: 50%; float: left">
          <pre>
            <code># CoffeeScript_Compiled.coffee canvasSize
= 300 $ -&gt; canvas = $('#myCanvas')[0] canvas.width = canvas.height = canvasSize
ctx = canvas.getContext '2d' ctx.fillStyle = '#002b36' ctx.fillRect(0,0,canvasSize,canvasSize)
ctx.font = '30px Arial' ctx.fillStyle = 'white' ctx.fillText("#myCanvas", 80, 150) </code>
          </pre>
        </div>
        <div style="border-left: #002b36 1px solid; width: 49%; float: left">
          <pre>
            <code>//
CoffeeScript_Compiled.js (function() { var canvasSize; canvasSize = 300; $(function()
{ var canvas, ctx; canvas = $('#myCanvas')[0]; canvas.width = canvas.height = canvasSize;
ctx = canvas.getContext('2d'); ctx.fillStyle = '#002b36'; ctx.fillRect(0, 0, canvasSize,
canvasSize); ctx.font = '30px Arial'; ctx.fillStyle = 'white'; return ctx.fillText("#myCanvas",
80, 150); }); }).call(this);</code>
          </pre>
        </div>
        <h3 style="clear: both">Circular
</h3>
        <p>
Now that the canvas is ready to draw on – let's get back to that arc. Like from the
Illustrator tutorial, I'm aiming to make a leaf-like object that can be duplicated
around a central axis.  First I'll create the right side of the leaf.
</p>
        <pre>
          <code># cache the math stuff pi = Math.PI cos = Math.cos sin = Math.sin $ -&gt;
canvas = $('#spriospectrum-arc')[0] ctx = canvas.getContext '2d' # make center of
the canvas the (0,0) coordinate ctx.translate(size/2, size/2) # radius of the complete
circle radius = size / 4 # create the arc shape ctx.beginPath() ctx.arc(0, 0, radius,
1.7 * pi, .3 * pi, false) ctx.closePath() # fill it in with a color ctx.fillStyle
= '#fdf6e3' ctx.fill()</code>
        </pre>
        <p>
The first bits are again to set up the canvas context – I'll omit those from now on. 
The first line of interest contains the <code><a href="http://www.html5canvastutorials.com/advanced/html5-canvas-transform-translate-tutorial/">translate</a></code> function
– this reorients the context to the specified point.  Anything drawn on the canvas
afterwards will treat this point as the center.  Here I pass in <code>size/2,
size/2</code> - which makes the center of the canvas the <code>0,0</code> coordinate.
</p>
        <p>
The next line computes a radius based off the size of the canvas – I simply did a
fourth of the canvas dimensions so that it would fit with room to spare.
</p>
        <p>
Next comes the definition of the arc's shape – or the path that the arc will make.
The first step is a call to <code><a href="http://www.html5canvastutorials.com/tutorials/html5-canvas-paths/">beginPath</a>()</code>. 
This is done so that the first point of the arc it is drawn as the beginning of the
shape.  If I had drawn anything else on the canvas before this (which I actually
have – more on that later), it would continue the previous path, drawing a line between
that last piece and the arc.  I've found it's easier to explicitly begin and
close the path rather than to assume it's a fresh canvas – especially when you start
composing more complex drawings.
</p>
        <p>
Finally – the actual call to <code><a href="http://www.html5canvastutorials.com/tutorials/html5-canvas-arcs/">arc</a></code>!
Since we've translated the canvas to center point we're passing in the <code>0,0</code> coordinate
so that the circle gets drawn in the exact middle.  Next comes the radius variable
which we've already defined. Now comes the tricky bit – the beginning and end angles
of the arc. Going back to the circle schematic – I'm defining the beginning point
slightly past the top (to the right), and the end point slightly before the bottom
(to the left).  By "slightly", I mean by <code>0.2</code> for each side. 
Multiply these values by π, and it's ready to be drawn! Oh – and the final parameter
indicates that it should be drawn counter-clockwise. Completely assembled, the call
looks like <code>arc(0, 0, radius, 1.7 * pi, .3 * pi, false)</code></p>
        <p>
Finally, a <code>fillStyle</code> is specified as a color using hex RGB and the arc
is drawn by calling <code><a href="http://www.html5canvastutorials.com/tutorials/html5-canvas-shape-fill/">fill</a>()</code>.
Voila!
</p>
        <figure>
          <canvas id="spriospectrum-arc">
            <img title="spriospectrum-arc" alt="spriospectrum-arc" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-arc_3.png" width="300" height="300" />
          </canvas>
          <figcaption>
Arc
</figcaption>
        </figure>
        <p>
Well... that seems like a lot of work to draw something so trivial!  It'll get
more interesting in a little bit...
</p>
        <h3>Leafy
</h3>
        <p>
The first half of the leaf has been drawn – now for the other half.  There are
a number of ways to go about this – I'll go over a few that I've found.  In this
first pass, we'll simply draw another arc on the opposite side of the circle.
</p>
        <pre>
          <code>ctx.beginPath() ctx.arc(0, 0, radius, 1.7 * pi, .3 * pi, false) ctx.arc(0,
0, radius, .7 * pi, 1.3 * pi, false) ctx.closePath()</code>
        </pre>
        <figure>
          <canvas id="spriospectrum-doubleArc">
            <img title="spriospectrum-doubleArc" alt="spriospectrum-doubleArc" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-doubleArc_3.png" width="300" height="300" />
          </canvas>
          <figcaption>
Double Arc
</figcaption>
        </figure>
        <p>
Ok – not a bad start.  This time I draw the same arc on the right as before and
then continue on with a second call to <code>arc</code> on the left side of the circle
– <code>arc(0, 0, radius, .7 * pi, 1.3 * pi, false)</code>.  The only differences
are the start and end angle.  Going clockwise, the first arc goes from 1.7π to
.3π, and then the second arc continues at .7π and ends at 1.3π.  Filling in this
path produces the shape seen above.
</p>
        <p>
The obvious problem is all that extra space in the middle of the circle – it's definitely
not leafy so it's got to go! I'll start over with just the arc on the right side. 
To allow us to easily figure out where the leaf will go, it'll be good to have an
easy-to-spot anchor point. For this, I chose the bottom bottom-most point of the leaf
which which will be located at <code>0,0</code>. All that's needed is a bit of maths.
</p>
        <p>
          <img style="background-image: none; border-right-width: 0px; margin: 10px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="arctrig" border="0" alt="arctrig" align="right" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/arctrig_20528432-e657-466d-81ef-808a0cfaaf5f.png" width="204" height="330" />It's
clear to see that the bottom-most point of the arc is below-and-right to the canvas
center point.  To do this, we'll move the coordinates for the center of the circle
up and to the left. But how much? To calculate, we'll use a little trig.  The
coordinates on a circle can be calculated, given the angle θ, with <code>x = cos(θ)</code> and <code>y
= sin(θ)</code>. So, the offset for x will be <code>-cos(.3π) * radius</code> and
for y will be <code>-sin(.3π) * radius</code>...
</p>
        <pre>
          <code>ctx.arc( -cos(.3 * pi) * radius, -sin(.3 * pi) * radius, radius, 1.7 *
pi, .3 * pi, false)</code>
        </pre>
        <figure>
          <canvas id="spriospectrum-arcBottomOrigin">
            <img title="spriospectrum-arcBottomOrigin" alt="spriospectrum-arcBottomOrigin" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-arcBottomOrigin_8fb6af10-c844-4f68-8d5f-fb668291949d.png" width="300" height="300" />
          </canvas>
          <figcaption>
Arc with Bottom at Origin
</figcaption>
        </figure>
        <p>
Success!  Now the same process for the left-side...
</p>
        <pre>
          <code>ctx.arc( -cos(.7 * pi) * radius, -sin(.7 * pi) * radius, radius, .7 * pi,
1.3 * pi, false)</code>
        </pre>
        <figure>
          <canvas id="spriospectrum-leaf">
            <img title="spriospectrum-leaf" alt="spriospectrum-leaf" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-leaf_c72b70ca-0fd0-43c8-ae98-1f99ed85f3d9.png" width="300" height="300" />
          </canvas>
          <figcaption>
Leaf
</figcaption>
        </figure>
        <h3>Rotate
</h3>
        <p>
Another way to skin this cat is to use the <code>rotate()</code> function to spin
the canvas around. Now I'll try drawing the first arc, flipping the context, and then
drawing the exact same arc.
</p>
        <pre>
          <code>drawArc = -&gt; ctx.arc( -cos(.3 * pi) * radius, -sin(.3 * pi) * radius,
radius, 1.7 * pi, .3 * pi, false) ctx.beginPath() drawArc() ctx.rotate(pi) # rotate
by half a circle drawArc() ctx.closePath()</code>
        </pre>
        <figure>
          <canvas id="spriospectrum-arcRotate">
            <img title="spriospectrum-arcRotate" alt="spriospectrum-arcRotate" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-arcRotate_1fabafd4-53c2-43c2-82bd-dc872e009905.png" width="300" height="300" />
          </canvas>
          <figcaption>
Rotated Arc
</figcaption>
        </figure>
        <p>
Kind of neat looking – but it obviously didn't turn out quite right.  It rotated
around the center and ended up both vertically and horizontally on the opposite side. 
This can be fixed with some additional translation...
</p>
        <pre>
          <code>startAngle = 1.7 * pi endAngle = .3 * pi drawArc = -&gt; ctx.arc(0, 0,
radius, startAngle, endAngle, false) ctx.beginPath() ctx.translate(-cos(endAngle)
* radius, -sin(endAngle) * radius) drawArc() ctx.rotate(pi) ctx.translate(-cos(endAngle)
* radius * 2, 0) drawArc() ctx.closePath()</code>
        </pre>
        <figure>
          <canvas id="spriospectrum-leafRotate">
            <img title="spriospectrum-leafRotate" alt="spriospectrum-leafRotate" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-leafRotate_83bef149-6e97-4ff4-9197-f7581acd5c17.png" width="300" height="300" />
          </canvas>
          <figcaption>
Rotated Arc for Leaf
</figcaption>
        </figure>
        <p>
This time I'm drawing the arc at <code>0,0</code> and doing a <code>translate</code> before
the first arc, and a <code>rotate</code> and <code>translate</code> before the second
arc.  It turns out to look the same the leaf before, but the code gets a bit
more muddy.  I prefer the previous implementation if this is what it takes. 
Also notice that I've added a few variables to capture the start and end angles –
this will be important in just a little bit...
</p>
        <p>
But first, you may have noticed that the height of the leaf, from bottom to top, is <em>some</em> length,
but <em>what</em> exact length is not immediately obvious.  It'd be helpful to
be able to define the leaf by a given height...
</p>
        <pre>
          <code>height = size/2 arcDelta = .2 arcAngles = start: (1.5 + arcDelta) * pi,
end: (.5 - arcDelta) * pi # a little trig to base the leaf's radius on a desired height
radius = height / (sin(arcAngles.end) * 2) ctx.beginPath() ctx.arc( -cos(arcAngles.end)
* radius, -sin(arcAngles.end) * radius, radius, arcAngles.start, arcAngles.end, false)
ctx.rotate(pi) ctx.arc( -cos(arcAngles.start) * radius, -sin(arcAngles.start) * radius,
radius, arcAngles.start, arcAngles.end, false) ctx.closePath()</code>
        </pre>
        <figure>
          <canvas id="spriospectrum-leafHeight">
            <img title="spriospectrum-leafHeight" alt="spriospectrum-leafHeight" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-leafHeight_ebfa3ea8-4ee8-4f8a-8549-2d2b23ac75c4.png" width="300" height="300" />
          </canvas>
          <figcaption>
Leaf using height
</figcaption>
        </figure>
        <p>
So, to compute the desired radius given for a given height, you can divide that height
by the ratio between the center point and the leaf's bottom, sin(endPoint), multiplied
by 2 to account for the top half:  <code>radius = height / (sin(arcAngles.end)
* 2)</code></p>
        <p>
Also note that I'm trying the rotate again, except I'm just repositioning the center
point of the second arc instead doing that messy translate.  This allows the
leaf to be defined by only one set of start and end angles which get reused in the
second arc.
</p>
        <p>
Finally, I've added another variable, arcDelta, to capture the offset between the
top and bottom angle.  So, rather than specifying 1.7π and .3π, now we only need
.2 which will get added to 1.5π and subtracted from .5π.
</p>
        <h3>Composing
</h3>
        <p>
Now to the fun stuff – the process to draw a leaf can now be encapsulated and we can
start drawing neat patterns.  Let's make a class for the leaf.
</p>
        <pre style="width: 60%; float: left">
          <code>class Leaf constructor: (height, @fillStyle
= '#fdf6e3', arcDelta = .2) -&gt; @arcAngles = start: (1.5 + arcDelta) * pi, end:
(.5 - arcDelta) * pi @radius = height / (sin(@arcAngles.end) * 2) draw: () -&gt; #
saving now allows the context's state to be restored # when we're done drawing ctx.save()
ctx.beginPath() ctx.arc( -cos(@arcAngles.end) * @radius, -sin(@arcAngles.end) * @radius,
@radius, @arcAngles.start, @arcAngles.end, false) ctx.rotate(pi) ctx.arc( -cos(@arcAngles.start)
* @radius, -sin(@arcAngles.start) * @radius, @radius, @arcAngles.start, @arcAngles.end,
false) ctx.closePath() ctx.fillStyle = @fillStyle ctx.fill() ctx.restore()</code>
        </pre>
        <pre style="border-left: #002b36 1px solid; width: 39%; float: left">
          <code> var
Leaf; Leaf = (function() { Leaf.name = 'Leaf'; function Leaf(height, fillStyle, arcDelta)
{ this.fillStyle = fillStyle != null ? fillStyle : '#fdf6e3'; if (arcDelta == null)
{ arcDelta = .2; } this.arcAngles = { start: (1.5 + arcDelta) * pi, end: (.5 - arcDelta)
* pi }; this.radius = height / (sin(this.arcAngles.end) * 2); } Leaf.prototype.draw
= function() { ctx.save(); ctx.beginPath(); ctx.arc(-cos(this.arcAngles.end) * this.radius,
-sin(this.arcAngles.end) * this.radius, this.radius, this.arcAngles.start, this.arcAngles.end,
false); ctx.rotate(pi); ctx.arc(-cos(this.arcAngles.start) * this.radius, -sin(this.arcAngles.start)
* this.radius, this.radius, this.arcAngles.start, this.arcAngles.end, false); ctx.closePath();
ctx.fillStyle = this.fillStyle; ctx.fill(); return ctx.restore(); }; return Leaf;
})();</code>
        </pre>
        <p style="clear: both">
I've added the compiled JavaScript for comparison to the right.  This is where <a href="http://coffeescript.org">CoffeeScript</a> starts
to spread its wings.  The <a href="http://coffeescript.org/#classes">class definition</a> is
much neater – the prototype functions are taken care of, the <code>this</code> repetitive-keystroke-injury-waiting-to-happen
is replaced with <code>@</code>, you've got default values for arguments – and this
is just scratching the surface.  So, now that we can easily draw some leaves...
</p>
        <pre>
          <code>ctx.translate(size/2, size) #bottom center leaves = [ new Leaf(size, '#c3d5eb')
new Leaf(size/9 * 8, '#648dcf', .25) new Leaf(size/5 * 4, '#12204d', .3) new Leaf(size/2,
'white', .35) ] leaf.draw() for leaf in leaves</code>
        </pre>
        <figure>
          <canvas id="spriospectrum-leafObject">
            <img title="spriospectrum-leafObject" alt="spriospectrum-leafObject" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-leafObject_064d4632-b88d-4cec-98f2-8b6783fa571a.png" width="300" height="300" />
          </canvas>
          <figcaption>
Leaf Object
</figcaption>
        </figure>
        <p>
Now we're cooking with gas!  (badum-ching - I'll be here all week) The next step
is to draw the spirograph from the Illustrator tutorial...
</p>
        <pre>
          <code>class SpiroLeaves constructor: (leafCount, radius, arcDelta = 1/10) -&gt;
@rotateAngle = (pi*2)/leafCount hsla = (i) -&gt; "hsla(#{i/leafCount*360}, 100%, 50%,
.2)" @leaves = (new Leaf(radius, hsla(i), arcDelta) for i in [leafCount..0]) draw:
(ctx) -&gt; ctx.save() for leaf in @leaves leaf.draw(ctx) ctx.rotate(@rotateAngle)
ctx.restore() ctx.globalCompositeOperation = "lighter" spiroLeaves = new SpiroLeaves(18,
size / 2) spiroLeaves.draw(ctx)</code>
        </pre>
        <figure>
          <canvas id="spriospectrum-spiroLeaves">
            <img title="spriospectrum-spiroLeaves" alt="spriospectrum-spiroLeaves" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-spiroLeaves_73187dbe-bd48-4666-b4be-3f5e451c3c2b.png" width="300" height="300" />
          </canvas>
          <figcaption>
Full on rainbow spirograph
</figcaption>
        </figure>
        <p>
A few notes...
</p>
        <ul>
          <li>
The SpiroLeaves constructor takes... 
<ul><li>
leafCount – which is how many leaves you want to be drawn... it is used to calculate
the angle to rotate between each leaf - <code>@rotateAngle = (pi*2)/leafCount</code></li><li>
radius – which is simply passed as the height for each leaf 
</li><li>
arcDelta – which how "skinny" or "squat" the leaves will be. Can be values between
0 and .5, with the larger the value, the skinnier.</li></ul></li>
          <li>
The hue of each leaf is calculated this function - <code>hsla = (i) -&gt; "hsla(#{i/leafCount*360},
100%, 50%, .2)"</code>. This produces a gradient hue between 0 and 360, with 100%
saturation, 50% lightness, and an alpha value of .2.  Read more <a href="http://www.w3.org/wiki/CSS/Properties/color/HSLA">here
at w3.org</a>. 
</li>
          <li>
Before drawing, the context is set to <code><a href="http://mudcu.be/journal/2011/04/globalcompositeoperation/">globalCompositeOperation</a> =
"lighter"</code> so that the colors in overlapping leaves will reinforce each other.</li>
        </ul>
        <p>
Finally – let's do something really cool and animate this.  I'll draw two overlapping
copies of the SpiroLeaves slowly rotating in opposite directions.
</p>
        <pre>
          <code>spiroLeaves = new SpiroLeaves(18, size) i = 0 drawFrame = -&gt; ctx.clearRect(0,0,size,
size) ctx.save() ctx.globalCompositeOperation = "darker" ctx.translate(size / 2 -
sin(i/200) * size/20, size / 2 - cos(i/200) * size/20) ctx.rotate(i/1000) spiroLeaves.draw(ctx)
ctx.restore() ctx.save() ctx.globalCompositeOperation = "lighter" ctx.translate(size
/ 2 + sin(i/100) * size/10, size / 2 + cos(i/100) * size/10) ctx.rotate(2-i/250) spiroLeaves.draw(ctx)
ctx.restore() i += 1 setInterval drawFrame, 25</code>
        </pre>
        <figure>
          <canvas id="spriospectrum-spiroSpin">
            <img title="spriospectrum-spiroSpin" alt="spriospectrum-spiroSpin" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-spiroSpin_thumb.gif" width="300" height="300" />
          </canvas>
          <figcaption>
Spin It
</figcaption>
        </figure>
        <p>
Nice! I've made a <a href="http://jsfiddle.net">jsfiddle</a> with this code setup
– feel free to tinker and make something of your own.  <a href="http://jsfiddle.net/poprhythm/g2WMu/">Here's
the link</a>.  Also, if you'd like to bring your CPU to its knees, make the canvas
full screen.
</p>
        <p>
This is my first foray into both HTM5 Canvas and CoffeeScript and I'm simply sharing
what I've learned.  So, please feel free to make any corrections and/or suggestions.
</p>
        <hr />
        <p>
HTML5 Canvas resources: <a href="http://www.html5canvastutorials.com/">HTML5 Canvas
Tutorials</a>, <a href="http://blog.nihilogic.dk/2009/02/html5-canvas-cheat-sheet.html">HTML5
Canvas Cheat Sheet</a></p>
        <p>
CoffeeScript resources:  <a href="http://coffeescript.org/">CoffeeScript.org</a>, <a href="http://coffeescriptcookbook.com/">CoffeeScript
Cookbook</a>, <a href="http://arcturo.github.com/library/coffeescript/">The Little
Book of CoffeeScript</a></p>
        <hr />
        <p>
P.S. – I had mentioned that I had already drawn something on the canvas before the
leaves.  This would be the grid pattern – here's the code:
</p>
        <pre>
          <code># draws a nice grid on the canvas drawGrid = (ctx, styles) -&gt; line =
(x1,y1,x2,y2) -&gt; ctx.beginPath() ctx.moveTo(x1,y1) ctx.lineTo(x2,y2) ctx.closePath()
ctx.stroke() divideAndStroke = (styles, divisions = 2) -&gt; if (styles.length &gt;
1) divideAndStroke(styles[1..], divisions * 2) ctx.strokeStyle = styles[0] for i in
[0..size] by (size/divisions) line(i,0,i,size) line(0,i,size,i) ctx.save() ctx.lineWidth
= 1; divideAndStroke styles ctx.restore() $ -&gt; # draw all the grids $('canvas').each
-&gt; this.width = size this.height = size ctx = this.getContext '2d' ctx.fillStyle
= '#002b36' ctx.fillRect(0,0,size,size) drawGrid(ctx, ['#657b83','#29434C','#073642','#073642'])</code>
        </pre>
        <script src="/content/scripts/SpiroSpectrum.js" type="text/javascript">
        </script>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=bafb3f1f-fed2-48f2-94b8-e5a2a8651044" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>Full on rainbow spirograph using HTML5 and CoffeeScript</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,bafb3f1f-fed2-48f2-94b8-e5a2a8651044.aspx</guid>
      <link>http://popcyclical.com/2012/06/29/FullOnRainbowSpirographUsingHTML5AndCoffeeScript.aspx</link>
      <pubDate>Fri, 29 Jun 2012 23:17:26 GMT</pubDate>
      <description>&lt;img style="display: inline" title="rainbowspirograph" alt="rainbowspirograph" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/rainbowspirograph.png" width="956" height="144"&gt; 
&lt;p&gt;
So intense. We've heard how HTML5's canvas element will provide device-independent
in-browser graphics – and now I want a taste! After seeing some &lt;a href="http://www.spielzeugz.de/html5/liquid-particles.html"&gt;magnificent&lt;/a&gt; &lt;a href="http://peterned.home.xs4all.nl/demooo/"&gt;demos&lt;/a&gt;,
I started wondering what the plumbing looks like.&amp;nbsp; I haven't touched any graphical
code since maybe 1994 in &lt;a href="http://en.wikipedia.org/wiki/QBASIC"&gt;QBasic&lt;/a&gt;,
so come along with me as I learn.
&lt;/p&gt;
&lt;p&gt;
Also, I'm giving &lt;a href="http://coffeescript.org/"&gt;CoffeeScript&lt;/a&gt; a spin. I saw
a presentation by &lt;a href="https://twitter.com/#!/dmohl"&gt;Daniel Mohl&lt;/a&gt; at &lt;a href="http://codestock.org/"&gt;Codestock&lt;/a&gt; a
few weeks ago and thought it was fantastic. You write in a terse-clean-"modern" language
and get the functionally equivalent JavaScript out the other end.&amp;nbsp; So long to
writing &lt;code&gt;function(){...}&lt;/code&gt; every three lines! Much of the syntax is based
on Ruby, so it's an easy language to read - I'll comment on any syntax that isn't
immediately obvious.
&lt;/p&gt;
&lt;p&gt;
But the important question is - what to draw?&amp;nbsp; I follow a few graphic design
blogs and remember seeing some neat &lt;a href="http://veerle.duoh.com/design/article/illustrator_full_spectrum_spirograph"&gt;geometric
patterns&lt;/a&gt; on &lt;a href="http://veerle.duoh.com"&gt;veerle's blog&lt;/a&gt; done in Adobe Illustrator.
These were inspired by the kaleidoscopic artwork of &lt;a href="http://crowquills.com/"&gt;Andy
Gilmore&lt;/a&gt; – check them out, some of the pieces are kind of hypnotic. The specific
creation that motivated Veerle's tutorial can be &lt;a href="http://crowquills.com/1061691/06-30-2008"&gt;seen
here&lt;/a&gt;. It has a beautiful simplicity. As Veerle mentions - we don't want to make
an exact replica, but instead use some of the patterns as a starting point of something
original.&lt;img style="background-image: none; border-right-width: 0px; margin: 10px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="HTML5 arc" border="0" alt="HTML5 arc" align="right" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/arc_3.png" width="304" height="304"&gt;
&lt;/p&gt;
&lt;p&gt;
The absolute first step is to draw a circle, just like it was in the Illustrator tutorial
by Veerle. Well, part of a circle. I found it easiest to get the desired results using
an "arc".&amp;nbsp; This is a term that simply means "a specific section along the side
of the circle".&amp;nbsp; What this entails for the HTML5 canvas is specifying the center
point of the circle, the radius, and the angles at the start and end the arc.&amp;nbsp;
My trigonometry knowledge has deteriorated over the years (if it ever existed to begin
with) – but this is pretty simple. The right-most point on the circle has an angle
of 0π, travelling clockwise to the bottom-most point is .5π, the left-most has 1π,
up to the top at 1.5π, and a full circle is (of course) 2π.&amp;nbsp; To draw a full circle,
you'd type in &lt;code&gt;context.arc(0,0,radius,0,Math.PI * 2)&lt;/code&gt;.&amp;nbsp; &lt;em&gt;Note:
the angles I learned in school were oriented counterclockwise, yet most of the examples
I've seen for HTML5 canvas are clockwise – most likely because the y-axis increases
in a downward direction instead of up.&amp;nbsp; I'll keep it clockwise here.&lt;/em&gt;
&lt;/p&gt;
&lt;h3&gt;Access the HTML5 Canvas using CoffeeScript
&lt;/h3&gt;
&lt;p&gt;
But what's this context, you ask? I might have lied about the first step – the super-absolute
first step will be to set up the HTML5 canvas object so that we can draw on it.&amp;nbsp;
Here's a complete example of a using CoffeeScript in a script tag with the in-browser
compiler to accomplish this.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt; &amp;lt;html&amp;gt; &amp;lt;head&amp;gt; &amp;lt;title&amp;gt;Full on rainbow
Spirograph&amp;lt;/title&amp;gt; &amp;lt;script src="scripts/jquery-1.7.2.min.js" type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script type="text/coffeescript"&amp;gt; canvasSize = 300 # shortcut for jquery's document
ready jQuery -&amp;gt; # get the canvas element (using jquery) canvas = $('#myCanvas')[0]
# set the width and height of the canvas element canvas.width = canvas.height = canvasSize
# get the API object for drawing on the canvas ctx = canvas.getContext '2d' # make
a dark background ctx.fillStyle = '#002b36' ctx.fillRect(0,0,canvasSize,canvasSize)
# write some text ctx.font = '30px Arial' ctx.fillStyle = 'white' ctx.fillText("#myCanvas",
80, 150) &amp;lt;/script&amp;gt; &amp;lt;/head&amp;gt; &amp;lt;body&amp;gt; &amp;lt;canvas id="myCanvas"&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;/body&amp;gt; &amp;lt;!-- download in-browser coffee-script compiler at --&amp;gt; &amp;lt;!--
https://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js --&amp;gt;
&amp;lt;!-- coffee-script.js goes AFTER all the CoffeeScript. --&amp;gt; &amp;lt;script type="text/javascript"
src="scripts/coffee-script.js"&amp;gt;&amp;lt;/script&amp;gt; &amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;img style="background-image: none; border-right-width: 0px; margin: 10px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="HTML5 canvas example" border="0" alt="HTML5 canvas example" align="right" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/canvas_1.png" width="244" height="298"&gt; 
&lt;p&gt;
This generates a page containing a dark 300x300 rectangle with "#myCanvas" written
in white. This is great for kicking the tires, but the script is getting compiled
down to JavaScript each time the page loads.&amp;nbsp; It's preferable to compile it ahead
of time.&amp;nbsp; With a little tooling this process becomes nearly transparent.&amp;nbsp;
In Visual Studio a great option is the &lt;a href="http://www.mindscapehq.com/products/web-workbench"&gt;Web
Workbench extension by Mindscape&lt;/a&gt;.&amp;nbsp; It automatically compiles your CoffeeScript
(and &lt;a href="http://sass-lang.com/"&gt;Sass&lt;/a&gt; and &lt;a href="http://lesscss.org/"&gt;LESS&lt;/a&gt;)
scripts each time the file is saved. After making this change, the code now looks
like...
&lt;/p&gt;
&lt;pre style="border-bottom: #002b36 1px solid"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt; &amp;lt;html&amp;gt;
&amp;lt;head&amp;gt; &amp;lt;title&amp;gt;Full on rainbow Spirograph&amp;lt;/title&amp;gt; &amp;lt;script src="scripts/jquery-1.7.2.min.js"
type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt; &amp;lt;script src="scripts/CoffeeScript_Compiled.js"
type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt; &amp;lt;/head&amp;gt; &amp;lt;body&amp;gt; &amp;lt;canvas id="myCanvas"&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;/body&amp;gt; &amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;div style="width: 50%; float: left"&gt;&lt;pre&gt;&lt;code&gt;# CoffeeScript_Compiled.coffee canvasSize
= 300 $ -&amp;gt; canvas = $('#myCanvas')[0] canvas.width = canvas.height = canvasSize
ctx = canvas.getContext '2d' ctx.fillStyle = '#002b36' ctx.fillRect(0,0,canvasSize,canvasSize)
ctx.font = '30px Arial' ctx.fillStyle = 'white' ctx.fillText("#myCanvas", 80, 150) &lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;div style="border-left: #002b36 1px solid; width: 49%; float: left"&gt;&lt;pre&gt;&lt;code&gt;//
CoffeeScript_Compiled.js (function() { var canvasSize; canvasSize = 300; $(function()
{ var canvas, ctx; canvas = $('#myCanvas')[0]; canvas.width = canvas.height = canvasSize;
ctx = canvas.getContext('2d'); ctx.fillStyle = '#002b36'; ctx.fillRect(0, 0, canvasSize,
canvasSize); ctx.font = '30px Arial'; ctx.fillStyle = 'white'; return ctx.fillText("#myCanvas",
80, 150); }); }).call(this);&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;h3 style="clear: both"&gt;Circular
&lt;/h3&gt;
&lt;p&gt;
Now that the canvas is ready to draw on – let's get back to that arc. Like from the
Illustrator tutorial, I'm aiming to make a leaf-like object that can be duplicated
around a central axis.&amp;nbsp; First I'll create the right side of the leaf.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# cache the math stuff pi = Math.PI cos = Math.cos sin = Math.sin $ -&amp;gt;
canvas = $('#spriospectrum-arc')[0] ctx = canvas.getContext '2d' # make center of
the canvas the (0,0) coordinate ctx.translate(size/2, size/2) # radius of the complete
circle radius = size / 4 # create the arc shape ctx.beginPath() ctx.arc(0, 0, radius,
1.7 * pi, .3 * pi, false) ctx.closePath() # fill it in with a color ctx.fillStyle
= '#fdf6e3' ctx.fill()&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
The first bits are again to set up the canvas context – I'll omit those from now on.&amp;nbsp;
The first line of interest contains the &lt;code&gt;&lt;a href="http://www.html5canvastutorials.com/advanced/html5-canvas-transform-translate-tutorial/"&gt;translate&lt;/a&gt;&lt;/code&gt; function
– this reorients the context to the specified point.&amp;nbsp; Anything drawn on the canvas
afterwards will treat this point as the center.&amp;nbsp; Here I pass in &lt;code&gt;size/2,
size/2&lt;/code&gt; - which makes the center of the canvas the &lt;code&gt;0,0&lt;/code&gt; coordinate.
&lt;/p&gt;
&lt;p&gt;
The next line computes a radius based off the size of the canvas – I simply did a
fourth of the canvas dimensions so that it would fit with room to spare.
&lt;/p&gt;
&lt;p&gt;
Next comes the definition of the arc's shape – or the path that the arc will make.
The first step is a call to &lt;code&gt;&lt;a href="http://www.html5canvastutorials.com/tutorials/html5-canvas-paths/"&gt;beginPath&lt;/a&gt;()&lt;/code&gt;.&amp;nbsp;
This is done so that the first point of the arc it is drawn as the beginning of the
shape.&amp;nbsp; If I had drawn anything else on the canvas before this (which I actually
have – more on that later), it would continue the previous path, drawing a line between
that last piece and the arc.&amp;nbsp; I've found it's easier to explicitly begin and
close the path rather than to assume it's a fresh canvas – especially when you start
composing more complex drawings.
&lt;/p&gt;
&lt;p&gt;
Finally – the actual call to &lt;code&gt;&lt;a href="http://www.html5canvastutorials.com/tutorials/html5-canvas-arcs/"&gt;arc&lt;/a&gt;&lt;/code&gt;!
Since we've translated the canvas to center point we're passing in the &lt;code&gt;0,0&lt;/code&gt; coordinate
so that the circle gets drawn in the exact middle.&amp;nbsp; Next comes the radius variable
which we've already defined. Now comes the tricky bit – the beginning and end angles
of the arc. Going back to the circle schematic – I'm defining the beginning point
slightly past the top (to the right), and the end point slightly before the bottom
(to the left).&amp;nbsp; By "slightly", I mean by &lt;code&gt;0.2&lt;/code&gt; for each side.&amp;nbsp;
Multiply these values by π, and it's ready to be drawn! Oh – and the final parameter
indicates that it should be drawn counter-clockwise. Completely assembled, the call
looks like &lt;code&gt;arc(0, 0, radius, 1.7 * pi, .3 * pi, false)&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Finally, a &lt;code&gt;fillStyle&lt;/code&gt; is specified as a color using hex RGB and the arc
is drawn by calling &lt;code&gt;&lt;a href="http://www.html5canvastutorials.com/tutorials/html5-canvas-shape-fill/"&gt;fill&lt;/a&gt;()&lt;/code&gt;.
Voila!
&lt;/p&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-arc"&gt;
&lt;img title="spriospectrum-arc" alt="spriospectrum-arc" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-arc_3.png" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Arc
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
Well... that seems like a lot of work to draw something so trivial!&amp;nbsp; It'll get
more interesting in a little bit...
&lt;/p&gt;
&lt;h3&gt;Leafy
&lt;/h3&gt;
&lt;p&gt;
The first half of the leaf has been drawn – now for the other half.&amp;nbsp; There are
a number of ways to go about this – I'll go over a few that I've found.&amp;nbsp; In this
first pass, we'll simply draw another arc on the opposite side of the circle.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ctx.beginPath() ctx.arc(0, 0, radius, 1.7 * pi, .3 * pi, false) ctx.arc(0,
0, radius, .7 * pi, 1.3 * pi, false) ctx.closePath()&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-doubleArc"&gt;
&lt;img title="spriospectrum-doubleArc" alt="spriospectrum-doubleArc" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-doubleArc_3.png" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Double Arc
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
Ok – not a bad start.&amp;nbsp; This time I draw the same arc on the right as before and
then continue on with a second call to &lt;code&gt;arc&lt;/code&gt; on the left side of the circle
– &lt;code&gt;arc(0, 0, radius, .7 * pi, 1.3 * pi, false)&lt;/code&gt;.&amp;nbsp; The only differences
are the start and end angle.&amp;nbsp; Going clockwise, the first arc goes from 1.7π to
.3π, and then the second arc continues at .7π and ends at 1.3π.&amp;nbsp; Filling in this
path produces the shape seen above.
&lt;/p&gt;
&lt;p&gt;
The obvious problem is all that extra space in the middle of the circle – it's definitely
not leafy so it's got to go! I'll start over with just the arc on the right side.&amp;nbsp;
To allow us to easily figure out where the leaf will go, it'll be good to have an
easy-to-spot anchor point. For this, I chose the bottom bottom-most point of the leaf
which which will be located at &lt;code&gt;0,0&lt;/code&gt;. All that's needed is a bit of maths.
&lt;/p&gt;
&lt;p&gt;
&lt;img style="background-image: none; border-right-width: 0px; margin: 10px 0px 0px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="arctrig" border="0" alt="arctrig" align="right" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/arctrig_20528432-e657-466d-81ef-808a0cfaaf5f.png" width="204" height="330"&gt;It's
clear to see that the bottom-most point of the arc is below-and-right to the canvas
center point.&amp;nbsp; To do this, we'll move the coordinates for the center of the circle
up and to the left. But how much? To calculate, we'll use a little trig.&amp;nbsp; The
coordinates on a circle can be calculated, given the angle θ, with &lt;code&gt;x = cos(θ)&lt;/code&gt; and &lt;code&gt;y
= sin(θ)&lt;/code&gt;. So, the offset for x will be &lt;code&gt;-cos(.3π) * radius&lt;/code&gt; and
for y will be &lt;code&gt;-sin(.3π) * radius&lt;/code&gt;...
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ctx.arc( -cos(.3 * pi) * radius, -sin(.3 * pi) * radius, radius, 1.7 *
pi, .3 * pi, false)&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-arcBottomOrigin"&gt;
&lt;img title="spriospectrum-arcBottomOrigin" alt="spriospectrum-arcBottomOrigin" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-arcBottomOrigin_8fb6af10-c844-4f68-8d5f-fb668291949d.png" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Arc with Bottom at Origin
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
Success!&amp;nbsp; Now the same process for the left-side...
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ctx.arc( -cos(.7 * pi) * radius, -sin(.7 * pi) * radius, radius, .7 * pi,
1.3 * pi, false)&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-leaf"&gt;
&lt;img title="spriospectrum-leaf" alt="spriospectrum-leaf" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-leaf_c72b70ca-0fd0-43c8-ae98-1f99ed85f3d9.png" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Leaf
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;h3&gt;Rotate
&lt;/h3&gt;
&lt;p&gt;
Another way to skin this cat is to use the &lt;code&gt;rotate()&lt;/code&gt; function to spin
the canvas around. Now I'll try drawing the first arc, flipping the context, and then
drawing the exact same arc.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;drawArc = -&amp;gt; ctx.arc( -cos(.3 * pi) * radius, -sin(.3 * pi) * radius,
radius, 1.7 * pi, .3 * pi, false) ctx.beginPath() drawArc() ctx.rotate(pi) # rotate
by half a circle drawArc() ctx.closePath()&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-arcRotate"&gt;
&lt;img title="spriospectrum-arcRotate" alt="spriospectrum-arcRotate" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-arcRotate_1fabafd4-53c2-43c2-82bd-dc872e009905.png" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Rotated Arc
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
Kind of neat looking – but it obviously didn't turn out quite right.&amp;nbsp; It rotated
around the center and ended up both vertically and horizontally on the opposite side.&amp;nbsp;
This can be fixed with some additional translation...
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;startAngle = 1.7 * pi endAngle = .3 * pi drawArc = -&amp;gt; ctx.arc(0, 0,
radius, startAngle, endAngle, false) ctx.beginPath() ctx.translate(-cos(endAngle)
* radius, -sin(endAngle) * radius) drawArc() ctx.rotate(pi) ctx.translate(-cos(endAngle)
* radius * 2, 0) drawArc() ctx.closePath()&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-leafRotate"&gt;
&lt;img title="spriospectrum-leafRotate" alt="spriospectrum-leafRotate" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-leafRotate_83bef149-6e97-4ff4-9197-f7581acd5c17.png" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Rotated Arc for Leaf
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
This time I'm drawing the arc at &lt;code&gt;0,0&lt;/code&gt; and doing a &lt;code&gt;translate&lt;/code&gt; before
the first arc, and a &lt;code&gt;rotate&lt;/code&gt; and &lt;code&gt;translate&lt;/code&gt; before the second
arc.&amp;nbsp; It turns out to look the same the leaf before, but the code gets a bit
more muddy.&amp;nbsp; I prefer the previous implementation if this is what it takes.&amp;nbsp;
Also notice that I've added a few variables to capture the start and end angles –
this will be important in just a little bit...
&lt;/p&gt;
&lt;p&gt;
But first, you may have noticed that the height of the leaf, from bottom to top, is &lt;em&gt;some&lt;/em&gt; length,
but &lt;em&gt;what&lt;/em&gt; exact length is not immediately obvious.&amp;nbsp; It'd be helpful to
be able to define the leaf by a given height...
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;height = size/2 arcDelta = .2 arcAngles = start: (1.5 + arcDelta) * pi,
end: (.5 - arcDelta) * pi # a little trig to base the leaf's radius on a desired height
radius = height / (sin(arcAngles.end) * 2) ctx.beginPath() ctx.arc( -cos(arcAngles.end)
* radius, -sin(arcAngles.end) * radius, radius, arcAngles.start, arcAngles.end, false)
ctx.rotate(pi) ctx.arc( -cos(arcAngles.start) * radius, -sin(arcAngles.start) * radius,
radius, arcAngles.start, arcAngles.end, false) ctx.closePath()&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-leafHeight"&gt;
&lt;img title="spriospectrum-leafHeight" alt="spriospectrum-leafHeight" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-leafHeight_ebfa3ea8-4ee8-4f8a-8549-2d2b23ac75c4.png" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Leaf using height
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
So, to compute the desired radius given for a given height, you can divide that height
by the ratio between the center point and the leaf's bottom, sin(endPoint), multiplied
by 2 to account for the top half:&amp;nbsp; &lt;code&gt;radius = height / (sin(arcAngles.end)
* 2)&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Also note that I'm trying the rotate again, except I'm just repositioning the center
point of the second arc instead doing that messy translate.&amp;nbsp; This allows the
leaf to be defined by only one set of start and end angles which get reused in the
second arc.
&lt;/p&gt;
&lt;p&gt;
Finally, I've added another variable, arcDelta, to capture the offset between the
top and bottom angle.&amp;nbsp; So, rather than specifying 1.7π and .3π, now we only need
.2 which will get added to 1.5π and subtracted from .5π.
&lt;/p&gt;
&lt;h3&gt;Composing
&lt;/h3&gt;
&lt;p&gt;
Now to the fun stuff – the process to draw a leaf can now be encapsulated and we can
start drawing neat patterns.&amp;nbsp; Let's make a class for the leaf.
&lt;/p&gt;
&lt;pre style="width: 60%; float: left"&gt;&lt;code&gt;class Leaf constructor: (height, @fillStyle
= '#fdf6e3', arcDelta = .2) -&amp;gt; @arcAngles = start: (1.5 + arcDelta) * pi, end:
(.5 - arcDelta) * pi @radius = height / (sin(@arcAngles.end) * 2) draw: () -&amp;gt; #
saving now allows the context's state to be restored # when we're done drawing ctx.save()
ctx.beginPath() ctx.arc( -cos(@arcAngles.end) * @radius, -sin(@arcAngles.end) * @radius,
@radius, @arcAngles.start, @arcAngles.end, false) ctx.rotate(pi) ctx.arc( -cos(@arcAngles.start)
* @radius, -sin(@arcAngles.start) * @radius, @radius, @arcAngles.start, @arcAngles.end,
false) ctx.closePath() ctx.fillStyle = @fillStyle ctx.fill() ctx.restore()&lt;/code&gt;&lt;/pre&gt;&lt;pre style="border-left: #002b36 1px solid; width: 39%; float: left"&gt;&lt;code&gt; var
Leaf; Leaf = (function() { Leaf.name = 'Leaf'; function Leaf(height, fillStyle, arcDelta)
{ this.fillStyle = fillStyle != null ? fillStyle : '#fdf6e3'; if (arcDelta == null)
{ arcDelta = .2; } this.arcAngles = { start: (1.5 + arcDelta) * pi, end: (.5 - arcDelta)
* pi }; this.radius = height / (sin(this.arcAngles.end) * 2); } Leaf.prototype.draw
= function() { ctx.save(); ctx.beginPath(); ctx.arc(-cos(this.arcAngles.end) * this.radius,
-sin(this.arcAngles.end) * this.radius, this.radius, this.arcAngles.start, this.arcAngles.end,
false); ctx.rotate(pi); ctx.arc(-cos(this.arcAngles.start) * this.radius, -sin(this.arcAngles.start)
* this.radius, this.radius, this.arcAngles.start, this.arcAngles.end, false); ctx.closePath();
ctx.fillStyle = this.fillStyle; ctx.fill(); return ctx.restore(); }; return Leaf;
})();&lt;/code&gt;&lt;/pre&gt;
&lt;p style="clear: both"&gt;
I've added the compiled JavaScript for comparison to the right.&amp;nbsp; This is where &lt;a href="http://coffeescript.org"&gt;CoffeeScript&lt;/a&gt; starts
to spread its wings.&amp;nbsp; The &lt;a href="http://coffeescript.org/#classes"&gt;class definition&lt;/a&gt; is
much neater – the prototype functions are taken care of, the &lt;code&gt;this&lt;/code&gt; repetitive-keystroke-injury-waiting-to-happen
is replaced with &lt;code&gt;@&lt;/code&gt;, you've got default values for arguments – and this
is just scratching the surface.&amp;nbsp; So, now that we can easily draw some leaves...
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ctx.translate(size/2, size) #bottom center leaves = [ new Leaf(size, '#c3d5eb')
new Leaf(size/9 * 8, '#648dcf', .25) new Leaf(size/5 * 4, '#12204d', .3) new Leaf(size/2,
'white', .35) ] leaf.draw() for leaf in leaves&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-leafObject"&gt;
&lt;img title="spriospectrum-leafObject" alt="spriospectrum-leafObject" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-leafObject_064d4632-b88d-4cec-98f2-8b6783fa571a.png" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Leaf Object
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
Now we're cooking with gas!&amp;nbsp; (badum-ching - I'll be here all week) The next step
is to draw the spirograph from the Illustrator tutorial...
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class SpiroLeaves constructor: (leafCount, radius, arcDelta = 1/10) -&amp;gt;
@rotateAngle = (pi*2)/leafCount hsla = (i) -&amp;gt; "hsla(#{i/leafCount*360}, 100%, 50%,
.2)" @leaves = (new Leaf(radius, hsla(i), arcDelta) for i in [leafCount..0]) draw:
(ctx) -&amp;gt; ctx.save() for leaf in @leaves leaf.draw(ctx) ctx.rotate(@rotateAngle)
ctx.restore() ctx.globalCompositeOperation = "lighter" spiroLeaves = new SpiroLeaves(18,
size / 2) spiroLeaves.draw(ctx)&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-spiroLeaves"&gt;
&lt;img title="spriospectrum-spiroLeaves" alt="spriospectrum-spiroLeaves" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-spiroLeaves_73187dbe-bd48-4666-b4be-3f5e451c3c2b.png" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Full on rainbow spirograph
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
A few notes...
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
The SpiroLeaves constructor takes... 
&lt;ul&gt;
&lt;li&gt;
leafCount – which is how many leaves you want to be drawn... it is used to calculate
the angle to rotate between each leaf - &lt;code&gt;@rotateAngle = (pi*2)/leafCount&lt;/code&gt; 
&lt;/li&gt;
&lt;li&gt;
radius – which is simply passed as the height for each leaf 
&lt;/li&gt;
&lt;li&gt;
arcDelta – which how "skinny" or "squat" the leaves will be. Can be values between
0 and .5, with the larger the value, the skinnier.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
The hue of each leaf is calculated this function - &lt;code&gt;hsla = (i) -&amp;gt; "hsla(#{i/leafCount*360},
100%, 50%, .2)"&lt;/code&gt;. This produces a gradient hue between 0 and 360, with 100%
saturation, 50% lightness, and an alpha value of .2.&amp;nbsp; Read more &lt;a href="http://www.w3.org/wiki/CSS/Properties/color/HSLA"&gt;here
at w3.org&lt;/a&gt;. 
&lt;/li&gt;
&lt;li&gt;
Before drawing, the context is set to &lt;code&gt;&lt;a href="http://mudcu.be/journal/2011/04/globalcompositeoperation/"&gt;globalCompositeOperation&lt;/a&gt; =
"lighter"&lt;/code&gt; so that the colors in overlapping leaves will reinforce each other.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Finally – let's do something really cool and animate this.&amp;nbsp; I'll draw two overlapping
copies of the SpiroLeaves slowly rotating in opposite directions.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;spiroLeaves = new SpiroLeaves(18, size) i = 0 drawFrame = -&amp;gt; ctx.clearRect(0,0,size,
size) ctx.save() ctx.globalCompositeOperation = "darker" ctx.translate(size / 2 -
sin(i/200) * size/20, size / 2 - cos(i/200) * size/20) ctx.rotate(i/1000) spiroLeaves.draw(ctx)
ctx.restore() ctx.save() ctx.globalCompositeOperation = "lighter" ctx.translate(size
/ 2 + sin(i/100) * size/10, size / 2 + cos(i/100) * size/10) ctx.rotate(2-i/250) spiroLeaves.draw(ctx)
ctx.restore() i += 1 setInterval drawFrame, 25&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;canvas id="spriospectrum-spiroSpin"&gt;
&lt;img title="spriospectrum-spiroSpin" alt="spriospectrum-spiroSpin" src="http://popcyclical.com/content/binary/Windows-Live-Writer/HTML5-full-spectrum-spirograph_BBD7/spriospectrum-spiroSpin_thumb.gif" width="300" height="300"&gt;
&lt;/canvas&gt;
&lt;figcaption&gt;
Spin It
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
Nice! I've made a &lt;a href="http://jsfiddle.net"&gt;jsfiddle&lt;/a&gt; with this code setup
– feel free to tinker and make something of your own.&amp;nbsp; &lt;a href="http://jsfiddle.net/poprhythm/g2WMu/"&gt;Here's
the link&lt;/a&gt;.&amp;nbsp; Also, if you'd like to bring your CPU to its knees, make the canvas
full screen.
&lt;/p&gt;
&lt;p&gt;
This is my first foray into both HTM5 Canvas and CoffeeScript and I'm simply sharing
what I've learned.&amp;nbsp; So, please feel free to make any corrections and/or suggestions.
&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;
HTML5 Canvas resources: &lt;a href="http://www.html5canvastutorials.com/"&gt;HTML5 Canvas
Tutorials&lt;/a&gt;, &lt;a href="http://blog.nihilogic.dk/2009/02/html5-canvas-cheat-sheet.html"&gt;HTML5
Canvas Cheat Sheet&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
CoffeeScript resources:&amp;nbsp; &lt;a href="http://coffeescript.org/"&gt;CoffeeScript.org&lt;/a&gt;, &lt;a href="http://coffeescriptcookbook.com/"&gt;CoffeeScript
Cookbook&lt;/a&gt;, &lt;a href="http://arcturo.github.com/library/coffeescript/"&gt;The Little
Book of CoffeeScript&lt;/a&gt;
&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;
P.S. – I had mentioned that I had already drawn something on the canvas before the
leaves.&amp;nbsp; This would be the grid pattern – here's the code:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# draws a nice grid on the canvas drawGrid = (ctx, styles) -&amp;gt; line =
(x1,y1,x2,y2) -&amp;gt; ctx.beginPath() ctx.moveTo(x1,y1) ctx.lineTo(x2,y2) ctx.closePath()
ctx.stroke() divideAndStroke = (styles, divisions = 2) -&amp;gt; if (styles.length &amp;gt;
1) divideAndStroke(styles[1..], divisions * 2) ctx.strokeStyle = styles[0] for i in
[0..size] by (size/divisions) line(i,0,i,size) line(0,i,size,i) ctx.save() ctx.lineWidth
= 1; divideAndStroke styles ctx.restore() $ -&amp;gt; # draw all the grids $('canvas').each
-&amp;gt; this.width = size this.height = size ctx = this.getContext '2d' ctx.fillStyle
= '#002b36' ctx.fillRect(0,0,size,size) drawGrid(ctx, ['#657b83','#29434C','#073642','#073642'])&lt;/code&gt;&lt;/pre&gt;&lt;script src="/content/scripts/SpiroSpectrum.js" type="text/javascript"&gt;&lt;/script&gt;&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=bafb3f1f-fed2-48f2-94b8-e5a2a8651044" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,bafb3f1f-fed2-48f2-94b8-e5a2a8651044.aspx</comments>
      <category>coffeescript</category>
      <category>html5</category>
      <category>visualization</category>
    </item>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=ff41614e-56ce-4e46-bc03-41dee971eed7</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,ff41614e-56ce-4e46-bc03-41dee971eed7.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,ff41614e-56ce-4e46-bc03-41dee971eed7.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=ff41614e-56ce-4e46-bc03-41dee971eed7</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I’ve been slowly making my way through the first 100 <a href="http://projecteuler.net/">Project
Euler</a> problems while learning F# in an attempt to be <a href="http://www.amazon.com/gp/product/020161622X?ie=UTF8&amp;tag=popcyclical-20&amp;linkCode=shr&amp;camp=213733&amp;creative=393185&amp;creativeASIN=020161622X">more
pragmatic</a> - and to try and prevent my grey matter from getting too stale. 
After many hours of keyboard-head-banging, I’m now getting to the point where I don’t
flail uselessly when beginning to type in some F# code – the <a href="http://msdn.microsoft.com/en-us/library/dd547125.aspx">pattern
matching</a>, <a href="http://msdn.microsoft.com/en-us/library/dd233183.aspx">automatic
generalization</a> and <a href="http://en.wikibooks.org/wiki/F_Sharp_Programming/Higher_Order_Functions">higher-order
functions</a> now feel like useful tools rather than strange curiosities.  Since
I’ve primarily coded in C# for many years, I’ve been using the book “<a href="http://www.amazon.com/gp/product/1933988924?ie=UTF8&amp;tag=popcyclical-20&amp;linkCode=shr&amp;camp=213733&amp;creative=393185&amp;creativeASIN=1933988924">Real
World Functional Programming</a>” by <a href="http://tomasp.net/">Tomas Petricek</a> as
a starting point – it’s been a pretty good read. So, for this post the code will be
in F#, but it’ll be secondary to the more general topic of problem solving for puzzle-type
scenarios commonly found on Project Euler.
</p>
        <p>
I found this <a href="http://projecteuler.net/problem=98">particular problem, #98</a>,
a bit more challenging than usual - and kind of fun to work through.  It involves
matching anagrams with square numbers using character replacement – here’s the full
description:
</p>
        <blockquote>
          <p>
By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively,
we form a square number: 1296 = 36<sup>2</sup>. What is remarkable is that, by using
the same digital substitutions, the anagram, RACE, also forms a square number: 9216
= 96<sup>2</sup>. We shall call CARE (and RACE) a square anagram word pair and specify
further that leading zeroes are not permitted, neither may a different letter have
the same digital value as another letter. 
</p>
          <p>
Using words.txt, a 16K text file containing nearly two-thousand common English words,
find all the square anagram word pairs (a palindromic word is NOT considered to be
an anagram of itself). 
</p>
          <p>
What is the largest square number formed by any member of such a pair?
</p>
        </blockquote>
        <p>
This is what I’d consider a pretty good puzzle – the elements (a word list and square
numbers) are easy enough to grasp, the way they’re related together is unique for
this scenario, and an effective solution does not immediately pop into mind. 
Well, it didn’t pop into <em>my </em>mind, at least.  So – where to begin?
</p>
        <p>
Many of the problems (at least the ones I’ve solved so far) on Project Euler involve
a few common steps to reach a solution:
</p>
        <ul>
          <li>
            <strong>Generate a set of input values for the problem</strong> – usually this will
be a large set of potential values, such as all the prime numbers below 10,000,000,
or in this case, 16K of words and a bunch of square numbers. 
</li>
          <li>
Given these inputs, <strong>build an algorithm that can test for the solution</strong>. 
</li>
          <li>
            <strong>Add constraints to reduce the size of the input set</strong> so that the solution
can quickly be found.  On modern hardware, this is usually under 1 second – but
anything under a minute is <a href="http://projecteuler.net/about">considered kosher</a>.</li>
        </ul>
        <h3>Input Values
</h3>
        <p>
The input values are easy here – they’ve provided the word list, and a sequence of
square numbers should be trivial.  First, reading the word list.  Instead
of placing the words each on a new line, the file instead contains a single line formatted
like:
</p>
        <blockquote>
          <pre>"A","ABILITY","ABLE","ABOUT","ABOVE","ABSENCE"...</pre>
        </blockquote>
        <p>
Ok – so it’ll take a little parsing.  No problem.
</p>
        <pre>
          <code>let words = System.IO.File.ReadAllLines(@"words.txt") |&gt; Array.collect
(fun line -&gt; line.Split(',')) |&gt; Array.map (fun w -&gt; w.Replace("\"", "").ToLower())</code>
        </pre>
        <p>
This loads the line from the file, splits the words by commas, and removes the quotations…
and I threw in making the words lowercase – since I hate having my puzzles constantly
shouting at me.  A little aside for the language particulars: the <code>|&gt;</code> is
the magical-looking-but-actually-quite-simple <a href="http://msdn.microsoft.com/en-us/magazine/cc164244.aspx#S6">pipeline
operator</a> – it passes the output from the function on the left to be input for
the function on the right. And the <code>fun –&gt;</code> is <a href="http://msdn.microsoft.com/en-us/library/dd233201.aspx">F#
syntax for lambda expressions</a>.  At the end of the pipeline comes a simple
array containing the parsed words. 
</p>
        <p>
  
</p>
        <p>
So for the rest of the input - the square numbers.  F# has the means to generate
an infinite sequence which can then be sliced and diced to get at the bits that are
needed.  The perfect squares can be generated with:
</p>
        <pre>
          <code>let allSquares = 
<br />
Seq.unfold(fun (square,odd) -&gt; Some(square, (square+odd, odd+2))) (0,1)</code>
        </pre>
        <p>
The square numbers are “<a href="http://msdn.microsoft.com/en-us/library/ee340363.aspx">unfolded</a>”
– that is, each element is calculated based on the result from the previous element,
like you’d do with.  Square numbers have a <a href="http://en.wikipedia.org/wiki/Square_number#Properties">property
where they can be generated by as the sum of a list of successive odd numbers</a>.
The <a href="http://msdn.microsoft.com/en-us/library/dd233200.aspx">tuple</a> of <code>(0,1)</code> on
the far right is fed in as an initial value, with <code>0</code> being the first “square”
number and <code>1</code> being the first odd number.  At each step of the unfold,
the odd number is increased by 2, and the square number is calculated by the adding
the previous odd number. So, the (square,odd) tuples being computed will look like:<code>(0,1),(1,3),(4,5),(9,7),(16,9)</code><font face="Lucida Sans Unicode">,
with only the squares being captured as output.  Works for me!</font></p>
        <p>
As with most simple-yet-effective bits of code, this one went through a couple of
refinements before nailing it.  The first pass looked like this:
</p>
        <pre>
          <code>Seq.unfold(fun i -&gt; Some(i, i + 1)) 0 |&gt; Seq.map (fun i -&gt;
i*i)</code>
        </pre>
        <p>
…where the squares are generated in two steps instead of one. The first bit unfolds
all the natural numbers from 0 to infinity (or more likely, maxint), and the second
part maps these each by squaring them.  It produces the same result, but is less
elegant because it uses more moving pieces.
</p>
        <p>
That’s all the input this problem should require – next, to design the…
</p>
        <h3>Success Algorithm
</h3>
        <p>
A useful bit of the Project Euler problem descriptions is that they usually include
an example which can be used as a test case for a solution algorithm. Here they’ve
provided:
</p>
        <pre>care, race // &lt;- anagrams map to<br />
1296, 9216 // &lt;- squares</pre>
        <p>
…with a replacement dictionary of <code>(c,1),(a,2),(r,9),(e,6)</code>.  It’s
important to note that the anagrams and squares might be symmetric, where the numbers
can be swapped (i.e. <code>(c,9),(a,2),(r,1),(e,6)</code> works as well), but there
are cases (such as the final answer) where this doesn’t hold.
</p>
        <p>
To devise an algorithm to test for an answer, the first step is to think it over before
doing any typing.  It’s better to have some notion of a strategy than to rush
in with the codes.  I struggle with adhering to this – it’s just too easy to
think “I’m so good, I’ll just figure it out as I program.”  I’ve found it’s more
productive to get away - get a pen and some paper and start sketching ideas, take
a walk, etc.  There’ll be plenty of time to work through all the details in code,
but it’s best to go in with a plan – a vague or even an incorrect strategy is better
than none at all.
</p>
        <p>
For this problem, I started with the idea of comparing each letter of the first word
with the first square number, building a replacement dictionary while iterating through
them.  If a valid replacement dictionary for the first set is found, it would
then be tested against the second word-square-number pair. Writing in algorithm in
F# meant I could treat the words as lists and iterate them using a common combination
of recursive function calls and pattern matching.
</p>
        <pre>
          <code>let rec getReplacementDictionary (sToT, tToS) (source, target) = match
source, target with // have already seen this exact mapping -&gt; skip it | s::ss,
t::tt when Map.containsKey s sToT &amp;&amp; (Map.find s sToT) = t -&gt; getReplacementDictionary
(sToT, tToS) (ss, tt) // have a mapping for the source, but it's not the target -&gt;
failure | s::_, _ when Map.containsKey s sToT -&gt; None // have a mapping for the
target, but it's not the source -&gt; failure | _::_, t::_ when Map.containsKey t
tToS -&gt; None // never before seen mapping -&gt; add it | s::ss, t::tt -&gt; getReplacementDictionary
(Map.add s t sToT, Map.add t s tToS) (ss, tt) // end of the line - a successful translation!
| [], [] -&gt; Some(sToT, tToS) | _ -&gt; raise(System.ArgumentException("words not
equal length")) </code>
        </pre>
        <p>
I’ve named the variables “source” and “target” – they’ll get passed the word and the
number, respectively.  They are “matched” against conditions using the patterns
seen on each line following the pipe “<code>|</code>” character.  The easiest
of these to grasp is near the end – “<code>| [], [] –&gt; Some(sToT, tToS)</code>“
which matches two empty lists, indicating that the words have been completely checked
and that there is a valid dictionary.  For the dictionary itself, I found that
it was necessary to keep tabs on both the source-to-target values (sToT) as well as
the target-to-source (tToS) values.  A bi-directional mapping structure would
be ideal, but it would have been more effort to construct that than to fudge it with
an extra variable.  If there is a better way to handle this, I’d be interested
to hear it…  
</p>
        <p>
At any rate, the result of this function will either be a failure - with the None
value - or with the completed dictionary(s) – the Some(sToT, tToS).  Testing
it against “care” and “1296” produces the expect result:
</p>
        <pre>
          <code>&gt; getReplacementDictionary (Map.empty, Map.empty) ("care" |&gt;
List.ofSeq, "1296" |&gt; List.ofSeq);; val it : (Map&lt;char,char&gt; * Map&lt;char,char&gt;)
option = Some (map [('a', '2'); ('c', '1'); ('e', '6'); ('r', '9')], map [('1', 'c');
('2', 'a'); ('6', 'e'); ('9', 'r')])</code>
        </pre>
        <p>
…and changing a digit in the number to one of the already mapped digits results (I’m
using 1292 which repeats the 2) in a failure:
</p>
        <pre>
          <code>&gt; getReplacementDictionary (Map.empty, Map.empty) ("care" |&gt;
List.ofSeq, "1292" |&gt; List.ofSeq);; val it : (Map&lt;char,char&gt; * Map&lt;char,char&gt;)
option = None</code>
        </pre>
        <p>
To test this dictionary against the second group, “race” and “9216”, the original
function may be reused because all of the character mappings will have been seen in
the first group and they will simply be verified via the first pattern.  
</p>
        <pre>
          <code>let dict = getReplacementDictionary (Map.empty, Map.empty) ("care"
|&gt; List.ofSeq, "1296" |&gt; List.ofSeq) getReplacementDictionary dict.Value ("race"
|&gt; List.ofSeq, "9216" |&gt; List.ofSeq);; val dict : (Map&lt;char,char&gt; * Map&lt;char,char&gt;)
option = Some (map [('a', '2'); ('c', '1'); ('e', '6'); ('r', '9')], map [('1', 'c');
('2', 'a'); ('6', 'e'); ('9', 'r')])</code>
        </pre>
        <p>
This is making an assumption that the input words are anagrams of each other – this
is an OK assumption to make for now.  Indeed, it can be even assumed that the
input data may be filtered for anagrams – I’ll cover that in the next section.
</p>
        <p>
I noticed that this could be further streamlined by simply appending the words and
the numbers together, since that is more-or-less what is occurring when calling it
twice.  And in that case, the function no longer needs to return the mapping
dictionary – just a simple boolean indicating if a valid dictionary can be applied
to the input.   So, the function can be modified as follows, making sure
to rename it:
</p>
        <pre>
          <code>let rec hasReplacementDictionary (sToT, tToS) (source, target) = match
source, target with | s::ss, t::tt when Map.containsKey s sToT &amp;&amp; (Map.find
s sToT) = t -&gt; hasReplacementDictionary (sToT, tToS) (ss, tt) | s::_, _ when Map.containsKey
s sToT -&gt; false | _::_, t::_ when Map.containsKey t tToS -&gt; false | s::ss, t::tt
-&gt; hasReplacementDictionary (Map.add s t sToT, Map.add t s tToS) (ss, tt) | [],
[] -&gt; true | _ -&gt; raise(System.ArgumentException("words not equal length"))</code>
        </pre>
        <p>
and run a test:
</p>
        <pre>
          <code>&gt; let los = List.ofSeq let s = List.append (List.ofSeq "care") (List.ofSeq
"race") let t = List.append (List.ofSeq "1296") (List.ofSeq "9216");; &gt; hasReplacementDictionary
(Map.empty, Map.empty) (s, t);; val it : bool = true</code>
        </pre>
        <p>
Success!  Now, having all the necessary input and a valid algorithm, it would
be possible to test every possibly combination of inputs to find the correct answer.  
</p>
        <h3>Input Constraints 
</h3>
        <p>
Project Euler problems are usually infeasible to answer without a computer. 
(There’s sometimes really smart math folks in the forums who will find clever ways
around this, but for the rest of us…)  
</p>
        <p>
How many combinations of the input data could there be, anyway?  There’s a total
of 1,786 words ranging in length from 1 to 14 characters, which leads to ~3.2 million
combinations of just the words.  My script to calculate the count of all square
numbers under 14 digits ran out of memory, but it turns out only up to 9 digit squares
are needed.  There are 31,623 of those.  The number of combinations would
be 1,786<sup>2</sup> × 31,623<sup>2</sup> ≈ 3.2E15.  That’s several thousand
billion – got to keep filtering or it’ll take a year!
</p>
        <p>
The next obvious step is to pair up the anagrams and discard the rest of the words. 
A simple way to do this is to alphabetically sort each character in each word and
group together the ones that are exactly the same.  For example “care” and “race”
will both map to “acer” – neat trick!  Here’s the code
</p>
        <pre>
          <code>let groupAnagrams ws = ws // sort by characters in each string and then
glue them back together |&gt; Seq.groupBy (Array.ofSeq &gt;&gt; Array.sort &gt;&gt;
(fun cs -&gt; new string(cs))) // take only the anagrams - where the number of words
is greater than one |&gt; Seq.map snd |&gt; Seq.filter (Seq.length &gt;&gt; ((&lt;)
1))</code>
        </pre>
        <p>
This is a great first step – but it’s not quite enough.  I want all the pairs
of anagrams and there are cases where there are more than 2 words that all have the
same letters.  For example, “post”, “spot” and “stop” will all group together. 
What I need is combinations of all the pairs – so I’ll end up with (“post”, “spot”),
(“spot”, stop”), and (“post”, “stop”).  Fortunately, I had already borrowed/stolen
a generic combination function that <a href="http://stackoverflow.com/a/4495708/99492">Tomas
had posted on Stack Overflow</a>.
</p>
        <pre>
          <code>let combinations size set = let rec combinations acc size set = seq { match
size, set with | n, x::xs -&gt; if n &gt; 0 then yield! combinations (x::acc) (n -
1) xs if n &gt;= 0 then yield! combinations acc n xs | 0, [] -&gt; yield acc | _,
[] -&gt; () } combinations [] size (set |&gt; List.ofSeq)</code>
        </pre>
        <p>
Now I can run all the whole list of anagram groups through the combinations algorithm
and produce a single list of anagram pairs:
</p>
        <pre>
          <code>let pairwiseTuples = Seq.collect ( combinations 2 &gt;&gt; Seq.map (fun
l -&gt; l.[0], l.[1]) ) </code>
        </pre>
        <p>
And indeed – it does its job:
</p>
        <pre>[|("cat", "act"); ... ("race", "care");
  ...
  ("spot", "post"); ("stop", "post"); ("stop", "spot"); 
  ...|]</pre>
        <p>
Running the words through this results in 44 pairs of anagrams with the lengthiest
pair being 9 letters long ("reduction", "introduce"). This is starting to sound reasonable
to process – and it’s where I got stuck for a bit.  Looping through all of the
squares for each pair still seems computationally prohibitive.  
</p>
        <p>
I walked away from it for the day and in the shower the next morning – “duh, the square
numbers can be bundled up as anagrams as well!"  These are the ah-ha moments
that make it all worthwhile.  A few examples – (“1024”, “2401”), (“14400”, “10404”). 
There turned out to still be quite a few for the larger digit counts (for example,
there are 70052 anagram pairs for square numbers with 9 digits), but since there are
so few words in the list that are above 5 characters long, it turned out to be OK.
</p>
        <p>
All was left was to write a few more lines to run all the equal-length anagram pairs
through the success function and find the result.  It ran in about a second on
my hardware, so that is an acceptable solution in my mind.  There are undoubtedly
numerous additional optimizations that could be applied – and perhaps even a way to
word it out on paper (I doubt it for this one) – so I’d be eager to hear any comments.
</p>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=ff41614e-56ce-4e46-bc03-41dee971eed7" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>How Do You Solve a Problem Like a Euler? Using F#</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,ff41614e-56ce-4e46-bc03-41dee971eed7.aspx</guid>
      <link>http://popcyclical.com/2012/04/26/HowDoYouSolveAProblemLikeAEulerUsingF.aspx</link>
      <pubDate>Thu, 26 Apr 2012 00:44:10 GMT</pubDate>
      <description>&lt;p&gt;
I’ve been slowly making my way through the first 100 &lt;a href="http://projecteuler.net/"&gt;Project
Euler&lt;/a&gt; problems while learning F# in an attempt to be &lt;a href="http://www.amazon.com/gp/product/020161622X?ie=UTF8&amp;amp;tag=popcyclical-20&amp;amp;linkCode=shr&amp;amp;camp=213733&amp;amp;creative=393185&amp;amp;creativeASIN=020161622X"&gt;more
pragmatic&lt;/a&gt; - and to try and prevent my grey matter from getting too stale.&amp;nbsp;
After many hours of keyboard-head-banging, I’m now getting to the point where I don’t
flail uselessly when beginning to type in some F# code – the &lt;a href="http://msdn.microsoft.com/en-us/library/dd547125.aspx"&gt;pattern
matching&lt;/a&gt;, &lt;a href="http://msdn.microsoft.com/en-us/library/dd233183.aspx"&gt;automatic
generalization&lt;/a&gt; and &lt;a href="http://en.wikibooks.org/wiki/F_Sharp_Programming/Higher_Order_Functions"&gt;higher-order
functions&lt;/a&gt; now feel like useful tools rather than strange curiosities.&amp;nbsp; Since
I’ve primarily coded in C# for many years, I’ve been using the book “&lt;a href="http://www.amazon.com/gp/product/1933988924?ie=UTF8&amp;amp;tag=popcyclical-20&amp;amp;linkCode=shr&amp;amp;camp=213733&amp;amp;creative=393185&amp;amp;creativeASIN=1933988924"&gt;Real
World Functional Programming&lt;/a&gt;” by &lt;a href="http://tomasp.net/"&gt;Tomas Petricek&lt;/a&gt; as
a starting point – it’s been a pretty good read. So, for this post the code will be
in F#, but it’ll be secondary to the more general topic of problem solving for puzzle-type
scenarios commonly found on Project Euler.
&lt;/p&gt;
&lt;p&gt;
I found this &lt;a href="http://projecteuler.net/problem=98"&gt;particular problem, #98&lt;/a&gt;,
a bit more challenging than usual - and kind of fun to work through.&amp;nbsp; It involves
matching anagrams with square numbers using character replacement – here’s the full
description:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively,
we form a square number: 1296 = 36&lt;sup&gt;2&lt;/sup&gt;. What is remarkable is that, by using
the same digital substitutions, the anagram, RACE, also forms a square number: 9216
= 96&lt;sup&gt;2&lt;/sup&gt;. We shall call CARE (and RACE) a square anagram word pair and specify
further that leading zeroes are not permitted, neither may a different letter have
the same digital value as another letter. 
&lt;p&gt;
Using words.txt, a 16K text file containing nearly two-thousand common English words,
find all the square anagram word pairs (a palindromic word is NOT considered to be
an anagram of itself). 
&lt;p&gt;
What is the largest square number formed by any member of such a pair?
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
This is what I’d consider a pretty good puzzle – the elements (a word list and square
numbers) are easy enough to grasp, the way they’re related together is unique for
this scenario, and an effective solution does not immediately pop into mind.&amp;nbsp;
Well, it didn’t pop into &lt;em&gt;my &lt;/em&gt;mind, at least.&amp;nbsp; So – where to begin?
&lt;/p&gt;
&lt;p&gt;
Many of the problems (at least the ones I’ve solved so far) on Project Euler involve
a few common steps to reach a solution:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Generate a set of input values for the problem&lt;/strong&gt; – usually this will
be a large set of potential values, such as all the prime numbers below 10,000,000,
or in this case, 16K of words and a bunch of square numbers. 
&lt;li&gt;
Given these inputs, &lt;strong&gt;build an algorithm that can test for the solution&lt;/strong&gt;. 
&lt;li&gt;
&lt;strong&gt;Add constraints to reduce the size of the input set&lt;/strong&gt; so that the solution
can quickly be found.&amp;nbsp; On modern hardware, this is usually under 1 second – but
anything under a minute is &lt;a href="http://projecteuler.net/about"&gt;considered kosher&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Input Values
&lt;/h3&gt;
&lt;p&gt;
The input values are easy here – they’ve provided the word list, and a sequence of
square numbers should be trivial.&amp;nbsp; First, reading the word list.&amp;nbsp; Instead
of placing the words each on a new line, the file instead contains a single line formatted
like:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;"A","ABILITY","ABLE","ABOUT","ABOVE","ABSENCE"...&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
Ok – so it’ll take a little parsing.&amp;nbsp; No problem.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let words = System.IO.File.ReadAllLines(@"words.txt") |&amp;gt; Array.collect
(fun line -&amp;gt; line.Split(',')) |&amp;gt; Array.map (fun w -&amp;gt; w.Replace("\"", "").ToLower())&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
This loads the line from the file, splits the words by commas, and removes the quotations…
and I threw in making the words lowercase – since I hate having my puzzles constantly
shouting at me.&amp;nbsp; A little aside for the language particulars: the &lt;code&gt;|&amp;gt;&lt;/code&gt; is
the magical-looking-but-actually-quite-simple &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc164244.aspx#S6"&gt;pipeline
operator&lt;/a&gt; – it passes the output from the function on the left to be input for
the function on the right. And the &lt;code&gt;fun –&amp;gt;&lt;/code&gt; is &lt;a href="http://msdn.microsoft.com/en-us/library/dd233201.aspx"&gt;F#
syntax for lambda expressions&lt;/a&gt;.&amp;nbsp; At the end of the pipeline comes a simple
array containing the parsed words. 
&lt;p&gt;
&amp;nbsp; 
&lt;p&gt;
So for the rest of the input - the square numbers.&amp;nbsp; F# has the means to generate
an infinite sequence which can then be sliced and diced to get at the bits that are
needed.&amp;nbsp; The perfect squares can be generated with:&lt;pre&gt;&lt;code&gt;let allSquares
= 
&lt;br&gt;
Seq.unfold(fun (square,odd) -&amp;gt; Some(square, (square+odd, odd+2))) (0,1)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
The square numbers are “&lt;a href="http://msdn.microsoft.com/en-us/library/ee340363.aspx"&gt;unfolded&lt;/a&gt;”
– that is, each element is calculated based on the result from the previous element,
like you’d do with.&amp;nbsp; Square numbers have a &lt;a href="http://en.wikipedia.org/wiki/Square_number#Properties"&gt;property
where they can be generated by as the sum of a list of successive odd numbers&lt;/a&gt;.
The &lt;a href="http://msdn.microsoft.com/en-us/library/dd233200.aspx"&gt;tuple&lt;/a&gt; of &lt;code&gt;(0,1)&lt;/code&gt; on
the far right is fed in as an initial value, with &lt;code&gt;0&lt;/code&gt; being the first “square”
number and &lt;code&gt;1&lt;/code&gt; being the first odd number.&amp;nbsp; At each step of the unfold,
the odd number is increased by 2, and the square number is calculated by the adding
the previous odd number. So, the (square,odd) tuples being computed will look like:&lt;code&gt;(0,1),(1,3),(4,5),(9,7),(16,9)&lt;/code&gt;&lt;font face="Lucida Sans Unicode"&gt;,
with only the squares being captured as output.&amp;nbsp; Works for me!&lt;/font&gt;
&lt;/p&gt;
&lt;p&gt;
As with most simple-yet-effective bits of code, this one went through a couple of
refinements before nailing it.&amp;nbsp; The first pass looked like this:&lt;pre&gt;&lt;code&gt;Seq.unfold(fun
i -&amp;gt; Some(i, i + 1)) 0 |&amp;gt; Seq.map (fun i -&amp;gt; i*i)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
…where the squares are generated in two steps instead of one. The first bit unfolds
all the natural numbers from 0 to infinity (or more likely, maxint), and the second
part maps these each by squaring them.&amp;nbsp; It produces the same result, but is less
elegant because it uses more moving pieces.
&lt;/p&gt;
&lt;p&gt;
That’s all the input this problem should require – next, to design the…
&lt;/p&gt;
&lt;h3&gt;Success Algorithm
&lt;/h3&gt;
&lt;p&gt;
A useful bit of the Project Euler problem descriptions is that they usually include
an example which can be used as a test case for a solution algorithm. Here they’ve
provided:
&lt;/p&gt;
&lt;pre&gt;care, race // &amp;lt;- anagrams map to&lt;br&gt;
1296, 9216 // &amp;lt;- squares&lt;/pre&gt;
&lt;p&gt;
…with a replacement dictionary of &lt;code&gt;(c,1),(a,2),(r,9),(e,6)&lt;/code&gt;.&amp;nbsp; It’s
important to note that the anagrams and squares might be symmetric, where the numbers
can be swapped (i.e. &lt;code&gt;(c,9),(a,2),(r,1),(e,6)&lt;/code&gt; works as well), but there
are cases (such as the final answer) where this doesn’t hold.
&lt;/p&gt;
&lt;p&gt;
To devise an algorithm to test for an answer, the first step is to think it over before
doing any typing.&amp;nbsp; It’s better to have some notion of a strategy than to rush
in with the codes.&amp;nbsp; I struggle with adhering to this – it’s just too easy to
think “I’m so good, I’ll just figure it out as I program.”&amp;nbsp; I’ve found it’s more
productive to get away - get a pen and some paper and start sketching ideas, take
a walk, etc.&amp;nbsp; There’ll be plenty of time to work through all the details in code,
but it’s best to go in with a plan – a vague or even an incorrect strategy is better
than none at all.
&lt;/p&gt;
&lt;p&gt;
For this problem, I started with the idea of comparing each letter of the first word
with the first square number, building a replacement dictionary while iterating through
them.&amp;nbsp; If a valid replacement dictionary for the first set is found, it would
then be tested against the second word-square-number pair. Writing in algorithm in
F# meant I could treat the words as lists and iterate them using a common combination
of recursive function calls and pattern matching.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let rec getReplacementDictionary (sToT, tToS) (source, target) = match
source, target with // have already seen this exact mapping -&amp;gt; skip it | s::ss,
t::tt when Map.containsKey s sToT &amp;amp;&amp;amp; (Map.find s sToT) = t -&amp;gt; getReplacementDictionary
(sToT, tToS) (ss, tt) // have a mapping for the source, but it's not the target -&amp;gt;
failure | s::_, _ when Map.containsKey s sToT -&amp;gt; None // have a mapping for the
target, but it's not the source -&amp;gt; failure | _::_, t::_ when Map.containsKey t
tToS -&amp;gt; None // never before seen mapping -&amp;gt; add it | s::ss, t::tt -&amp;gt; getReplacementDictionary
(Map.add s t sToT, Map.add t s tToS) (ss, tt) // end of the line - a successful translation!
| [], [] -&amp;gt; Some(sToT, tToS) | _ -&amp;gt; raise(System.ArgumentException("words not
equal length")) &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
I’ve named the variables “source” and “target” – they’ll get passed the word and the
number, respectively.&amp;nbsp; They are “matched” against conditions using the patterns
seen on each line following the pipe “&lt;code&gt;|&lt;/code&gt;” character.&amp;nbsp; The easiest
of these to grasp is near the end – “&lt;code&gt;| [], [] –&amp;gt; Some(sToT, tToS)&lt;/code&gt;“
which matches two empty lists, indicating that the words have been completely checked
and that there is a valid dictionary.&amp;nbsp; For the dictionary itself, I found that
it was necessary to keep tabs on both the source-to-target values (sToT) as well as
the target-to-source (tToS) values.&amp;nbsp; A bi-directional mapping structure would
be ideal, but it would have been more effort to construct that than to fudge it with
an extra variable.&amp;nbsp; If there is a better way to handle this, I’d be interested
to hear it…&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
At any rate, the result of this function will either be a failure - with the None
value - or with the completed dictionary(s) – the Some(sToT, tToS).&amp;nbsp; Testing
it against “care” and “1296” produces the expect result:&lt;pre&gt;&lt;code&gt;&amp;gt; getReplacementDictionary
(Map.empty, Map.empty) ("care" |&amp;gt; List.ofSeq, "1296" |&amp;gt; List.ofSeq);; val it
: (Map&amp;lt;char,char&amp;gt; * Map&amp;lt;char,char&amp;gt;) option = Some (map [('a', '2'); ('c',
'1'); ('e', '6'); ('r', '9')], map [('1', 'c'); ('2', 'a'); ('6', 'e'); ('9', 'r')])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
…and changing a digit in the number to one of the already mapped digits results (I’m
using 1292 which repeats the 2) in a failure:&lt;pre&gt;&lt;code&gt;&amp;gt; getReplacementDictionary
(Map.empty, Map.empty) ("care" |&amp;gt; List.ofSeq, "1292" |&amp;gt; List.ofSeq);; val it
: (Map&amp;lt;char,char&amp;gt; * Map&amp;lt;char,char&amp;gt;) option = None&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
To test this dictionary against the second group, “race” and “9216”, the original
function may be reused because all of the character mappings will have been seen in
the first group and they will simply be verified via the first pattern.&amp;nbsp; &lt;pre&gt;&lt;code&gt;let
dict = getReplacementDictionary (Map.empty, Map.empty) ("care" |&amp;gt; List.ofSeq, "1296"
|&amp;gt; List.ofSeq) getReplacementDictionary dict.Value ("race" |&amp;gt; List.ofSeq, "9216"
|&amp;gt; List.ofSeq);; val dict : (Map&amp;lt;char,char&amp;gt; * Map&amp;lt;char,char&amp;gt;) option
= Some (map [('a', '2'); ('c', '1'); ('e', '6'); ('r', '9')], map [('1', 'c'); ('2',
'a'); ('6', 'e'); ('9', 'r')])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
This is making an assumption that the input words are anagrams of each other – this
is an OK assumption to make for now.&amp;nbsp; Indeed, it can be even assumed that the
input data may be filtered for anagrams – I’ll cover that in the next section.
&lt;/p&gt;
&lt;p&gt;
I noticed that this could be further streamlined by simply appending the words and
the numbers together, since that is more-or-less what is occurring when calling it
twice.&amp;nbsp; And in that case, the function no longer needs to return the mapping
dictionary – just a simple boolean indicating if a valid dictionary can be applied
to the input.&amp;nbsp;&amp;nbsp; So, the function can be modified as follows, making sure
to rename it:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let rec hasReplacementDictionary (sToT, tToS) (source, target) = match
source, target with | s::ss, t::tt when Map.containsKey s sToT &amp;amp;&amp;amp; (Map.find
s sToT) = t -&amp;gt; hasReplacementDictionary (sToT, tToS) (ss, tt) | s::_, _ when Map.containsKey
s sToT -&amp;gt; false | _::_, t::_ when Map.containsKey t tToS -&amp;gt; false | s::ss, t::tt
-&amp;gt; hasReplacementDictionary (Map.add s t sToT, Map.add t s tToS) (ss, tt) | [],
[] -&amp;gt; true | _ -&amp;gt; raise(System.ArgumentException("words not equal length"))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
and run a test:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt; let los = List.ofSeq let s = List.append (List.ofSeq "care") (List.ofSeq
"race") let t = List.append (List.ofSeq "1296") (List.ofSeq "9216");; &amp;gt; hasReplacementDictionary
(Map.empty, Map.empty) (s, t);; val it : bool = true&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
Success!&amp;nbsp; Now, having all the necessary input and a valid algorithm, it would
be possible to test every possibly combination of inputs to find the correct answer.&amp;nbsp; 
&lt;/p&gt;
&lt;h3&gt;Input Constraints 
&lt;/h3&gt;
&lt;p&gt;
Project Euler problems are usually infeasible to answer without a computer.&amp;nbsp;
(There’s sometimes really smart math folks in the forums who will find clever ways
around this, but for the rest of us…)&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
How many combinations of the input data could there be, anyway?&amp;nbsp; There’s a total
of 1,786 words ranging in length from 1 to 14 characters, which leads to ~3.2 million
combinations of just the words.&amp;nbsp; My script to calculate the count of all square
numbers under 14 digits ran out of memory, but it turns out only up to 9 digit squares
are needed.&amp;nbsp; There are 31,623 of those.&amp;nbsp; The number of combinations would
be 1,786&lt;sup&gt;2&lt;/sup&gt; × 31,623&lt;sup&gt;2&lt;/sup&gt; ≈ 3.2E15.&amp;nbsp; That’s several thousand
billion – got to keep filtering or it’ll take a year!
&lt;/p&gt;
&lt;p&gt;
The next obvious step is to pair up the anagrams and discard the rest of the words.&amp;nbsp;
A simple way to do this is to alphabetically sort each character in each word and
group together the ones that are exactly the same.&amp;nbsp; For example “care” and “race”
will both map to “acer” – neat trick!&amp;nbsp; Here’s the code
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let groupAnagrams ws = ws // sort by characters in each string and then
glue them back together |&amp;gt; Seq.groupBy (Array.ofSeq &amp;gt;&amp;gt; Array.sort &amp;gt;&amp;gt;
(fun cs -&amp;gt; new string(cs))) // take only the anagrams - where the number of words
is greater than one |&amp;gt; Seq.map snd |&amp;gt; Seq.filter (Seq.length &amp;gt;&amp;gt; ((&amp;lt;)
1))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
This is a great first step – but it’s not quite enough.&amp;nbsp; I want all the pairs
of anagrams and there are cases where there are more than 2 words that all have the
same letters.&amp;nbsp; For example, “post”, “spot” and “stop” will all group together.&amp;nbsp;
What I need is combinations of all the pairs – so I’ll end up with (“post”, “spot”),
(“spot”, stop”), and (“post”, “stop”).&amp;nbsp; Fortunately, I had already borrowed/stolen
a generic combination function that &lt;a href="http://stackoverflow.com/a/4495708/99492"&gt;Tomas
had posted on Stack Overflow&lt;/a&gt;.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let combinations size set = let rec combinations acc size set = seq { match
size, set with | n, x::xs -&amp;gt; if n &amp;gt; 0 then yield! combinations (x::acc) (n -
1) xs if n &amp;gt;= 0 then yield! combinations acc n xs | 0, [] -&amp;gt; yield acc | _,
[] -&amp;gt; () } combinations [] size (set |&amp;gt; List.ofSeq)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
Now I can run all the whole list of anagram groups through the combinations algorithm
and produce a single list of anagram pairs:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let pairwiseTuples = Seq.collect ( combinations 2 &amp;gt;&amp;gt; Seq.map (fun
l -&amp;gt; l.[0], l.[1]) ) &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
And indeed – it does its job:
&lt;/p&gt;
&lt;pre&gt;[|("cat", "act"); ... ("race", "care");
  ...
  ("spot", "post"); ("stop", "post"); ("stop", "spot"); 
  ...|]&lt;/pre&gt;
&lt;p&gt;
Running the words through this results in 44 pairs of anagrams with the lengthiest
pair being 9 letters long ("reduction", "introduce"). This is starting to sound reasonable
to process – and it’s where I got stuck for a bit.&amp;nbsp; Looping through all of the
squares for each pair still seems computationally prohibitive.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
I walked away from it for the day and in the shower the next morning – “duh, the square
numbers can be bundled up as anagrams as well!"&amp;nbsp; These are the ah-ha moments
that make it all worthwhile.&amp;nbsp; A few examples – (“1024”, “2401”), (“14400”, “10404”).&amp;nbsp;
There turned out to still be quite a few for the larger digit counts (for example,
there are 70052 anagram pairs for square numbers with 9 digits), but since there are
so few words in the list that are above 5 characters long, it turned out to be OK.
&lt;/p&gt;
&lt;p&gt;
All was left was to write a few more lines to run all the equal-length anagram pairs
through the success function and find the result.&amp;nbsp; It ran in about a second on
my hardware, so that is an acceptable solution in my mind.&amp;nbsp; There are undoubtedly
numerous additional optimizations that could be applied – and perhaps even a way to
word it out on paper (I doubt it for this one) – so I’d be eager to hear any comments.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=ff41614e-56ce-4e46-bc03-41dee971eed7" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,ff41614e-56ce-4e46-bc03-41dee971eed7.aspx</comments>
      <category>fsharp</category>
      <category>projecteuler</category>
    </item>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=368068e5-b898-46f6-90f6-d34c665d7db4</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,368068e5-b898-46f6-90f6-d34c665d7db4.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,368068e5-b898-46f6-90f6-d34c665d7db4.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=368068e5-b898-46f6-90f6-d34c665d7db4</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In <a href="http://weblogs.asp.net/jgalloway/">Jon Galloway’s</a><a href="http://weblogs.asp.net/jgalloway/archive/2005/09/27/426087.aspx">Splitting
Camel Case with RegEx</a> blog post, he introduced a simple regular expression replacement
which can split “ThisIsInPascalCase” into “This Is In Pascal Case”.  Here’s the
original code:
</p>
        <pre>
          <code>output = System.Text.RegularExpressions.Regex.Replace( input, "([A-Z])",
" $1", System.Text.RegularExpressions.RegexOptions.Compiled).Trim(); </code>
        </pre>
        <p>
Simple and effective.  Matches any capital letters and inserts a space before
them.  But there’s room for improvement.  First, the call to <code>String.Trim()</code> to
remove any spaces potentially added if the first letter is uppercase – this can be
handled with a <a href="http://msdn.microsoft.com/en-us/library/az24scfc.aspx#grouping_constructs">“Match
if prefix is absent” group</a> containing the “beginning of line” character <code>^</code>. 
This prevents any matches from occurring on the first character, which eliminates
the need for the <code>String.Trim()</code> call.  The formal name for this grouping
construct is “Zero-width negative lookbehind assertion”, but just think of it as “if
you see what’s in here, don’t match the next thing”.
</p>
        <pre>
          <code> (?&lt;!^)([A-Z])</code>
        </pre>
        <p>
Next - there’s a potential issue with how acronyms get handled with this.  Given
this fictional book title: “WCFForNoobs” – the split will occur on each uppercase
letter resulting in “W C F For Noobs”.  The fix is simple, though – require that
uppercase letters be followed by a lowercase:
</p>
        <pre>
          <code> (?&lt;!^)([A-Z][a-z]) </code>
        </pre>
        <p>
…Now it’ll result in “WCF For Noobs” (aren’t we all!).  But now it won’t add
a space before the acronym – for “LearnWCFInSixEasyMonths”, the result will be “LearnWCF
In Six Easy Months”.  No problem – add an alternate match for a lowercase letter
coming before the uppercase letter.  The replace pattern makes this more difficult
– we don’t want the space to go before the lowercase letter, we want it between the
lowercase and the first capital letter of the acronym.  RegEx can handle this
with another lookbehind match group – “Match prefix but exclude it” - <code>(?&lt;=)</code>. 
This allows the match to occur on the lowercase-uppercase pair, but only the uppercase
portion will get matched, so when it comes time to run the replacement, the space
will get inserted between the two letters.  By itself, that’ll look like this:
</p>
        <pre>
          <code> ((?&lt;=[a-z])[A-Z]) </code>
        </pre>
        <p>
Great!  But this needs to be combined with previous expression.  Easy accomplished
with an either/or match using the vertical bar “or” construct:
</p>
        <pre>
          <code> (?&lt;!^)([A-Z][a-z]|(?&lt;=[a-z])[A-Z]) </code>
        </pre>
        <p>
The example “LearnWCFInSixEasyMonths” will now be split into “Learn WCF In Six Easy
Months”.  These same techniques can be used for additional splits – perhaps on
numbers or underscores.  More generally, <a href="http://www.regular-expressions.info/lookaround.html">lookbehind
and lookahead are great tools</a> to have in your RegEx toolbelt.
</p>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=368068e5-b898-46f6-90f6-d34c665d7db4" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>Splitting Pascal/Camel Case with RegEx Enhancements</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,368068e5-b898-46f6-90f6-d34c665d7db4.aspx</guid>
      <link>http://popcyclical.com/2010/09/12/SplittingPascalCamelCaseWithRegExEnhancements.aspx</link>
      <pubDate>Sun, 12 Sep 2010 02:03:15 GMT</pubDate>
      <description>&lt;p&gt;
In &lt;a href="http://weblogs.asp.net/jgalloway/"&gt;Jon Galloway’s&lt;/a&gt; &lt;a href="http://weblogs.asp.net/jgalloway/archive/2005/09/27/426087.aspx"&gt;Splitting
Camel Case with RegEx&lt;/a&gt; blog post, he introduced a simple regular expression replacement
which can split “ThisIsInPascalCase” into “This Is In Pascal Case”.&amp;nbsp; Here’s the
original code:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;output = System.Text.RegularExpressions.Regex.Replace( input, "([A-Z])",
" $1", System.Text.RegularExpressions.RegexOptions.Compiled).Trim(); &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
Simple and effective.&amp;nbsp; Matches any capital letters and inserts a space before
them.&amp;nbsp; But there’s room for improvement.&amp;nbsp; First, the call to &lt;code&gt;String.Trim()&lt;/code&gt; to
remove any spaces potentially added if the first letter is uppercase – this can be
handled with a &lt;a href="http://msdn.microsoft.com/en-us/library/az24scfc.aspx#grouping_constructs"&gt;“Match
if prefix is absent” group&lt;/a&gt; containing the “beginning of line” character &lt;code&gt;^&lt;/code&gt;.&amp;nbsp;
This prevents any matches from occurring on the first character, which eliminates
the need for the &lt;code&gt;String.Trim()&lt;/code&gt; call.&amp;nbsp; The formal name for this grouping
construct is “Zero-width negative lookbehind assertion”, but just think of it as “if
you see what’s in here, don’t match the next thing”.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; (?&amp;lt;!^)([A-Z])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
Next - there’s a potential issue with how acronyms get handled with this.&amp;nbsp; Given
this fictional book title: “WCFForNoobs” – the split will occur on each uppercase
letter resulting in “W C F For Noobs”.&amp;nbsp; The fix is simple, though – require that
uppercase letters be followed by a lowercase:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; (?&amp;lt;!^)([A-Z][a-z]) &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
…Now it’ll result in “WCF For Noobs” (aren’t we all!).&amp;nbsp; But now it won’t add
a space before the acronym – for “LearnWCFInSixEasyMonths”, the result will be “LearnWCF
In Six Easy Months”.&amp;nbsp; No problem – add an alternate match for a lowercase letter
coming before the uppercase letter.&amp;nbsp; The replace pattern makes this more difficult
– we don’t want the space to go before the lowercase letter, we want it between the
lowercase and the first capital letter of the acronym.&amp;nbsp; RegEx can handle this
with another lookbehind match group – “Match prefix but exclude it” - &lt;code&gt;(?&amp;lt;=)&lt;/code&gt;.&amp;nbsp;
This allows the match to occur on the lowercase-uppercase pair, but only the uppercase
portion will get matched, so when it comes time to run the replacement, the space
will get inserted between the two letters.&amp;nbsp; By itself, that’ll look like this:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; ((?&amp;lt;=[a-z])[A-Z]) &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
Great!&amp;nbsp; But this needs to be combined with previous expression.&amp;nbsp; Easy accomplished
with an either/or match using the vertical bar “or” construct:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; (?&amp;lt;!^)([A-Z][a-z]|(?&amp;lt;=[a-z])[A-Z]) &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
The example “LearnWCFInSixEasyMonths” will now be split into “Learn WCF In Six Easy
Months”.&amp;nbsp; These same techniques can be used for additional splits – perhaps on
numbers or underscores.&amp;nbsp; More generally, &lt;a href="http://www.regular-expressions.info/lookaround.html"&gt;lookbehind
and lookahead are great tools&lt;/a&gt; to have in your RegEx toolbelt.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=368068e5-b898-46f6-90f6-d34c665d7db4" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,368068e5-b898-46f6-90f6-d34c665d7db4.aspx</comments>
      <category>c#</category>
      <category>regex</category>
    </item>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=81052414-02a8-471b-a1ea-6797594e24ba</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,81052414-02a8-471b-a1ea-6797594e24ba.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,81052414-02a8-471b-a1ea-6797594e24ba.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=81052414-02a8-471b-a1ea-6797594e24ba</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <em>With tongue implementation injected dynamically into cheek object</em>
          <a href="http://www.jetbrains.com/resharper/">
            <img style="border: 0px none; margin: 10px 15px 0px 0px; display: inline;" title="ReShephard" alt="ReShephard" src="http://popcyclical.com/content/binary/images/PoemforReSharper_F225/ReShephard.jpg" align="right" border="0" height="260" width="230" />
          </a>…
</p>
        <p>
ReSharper is my shepherd, 
<br />
I shall not want; 
<br />
He lets me apply quick refactors. 
<br />
He leads me to errors before compile; 
<br />
He cleans up my code. 
<br />
He navigates me in paths of inheritance 
<br />
for each namespace. 
</p>
        <p>
Even though I strive to remove cruft 
<br />
of the brownfield app, 
<br />
I fear no error; 
<br />
for You are in my IDE; 
<br />
Your red and Your green unit tests, they comfort me. 
</p>
        <p>
Surely correctness and maintainability shall follow me 
<br />
all the deployments of my app; 
<br />
and I shall dwell favorably in the thoughts of my 
<br />
Users forever. 
</p>
        <p>
          <em>Sum(23)</em>
        </p>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=81052414-02a8-471b-a1ea-6797594e24ba" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>Poem for ReSharper</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,81052414-02a8-471b-a1ea-6797594e24ba.aspx</guid>
      <link>http://popcyclical.com/2010/08/27/PoemForReSharper.aspx</link>
      <pubDate>Fri, 27 Aug 2010 21:19:31 GMT</pubDate>
      <description>&lt;p&gt;
&lt;em&gt;With tongue implementation injected dynamically into cheek object&lt;/em&gt;&lt;a href="http://www.jetbrains.com/resharper/"&gt;&lt;img style="border: 0px none; margin: 10px 15px 0px 0px; display: inline;" title="ReShephard" alt="ReShephard" src="http://popcyclical.com/content/binary/images/PoemforReSharper_F225/ReShephard.jpg" align="right" border="0" height="260" width="230"&gt;&lt;/a&gt;…
&lt;/p&gt;
&lt;p&gt;
ReSharper is my shepherd, 
&lt;br&gt;
I shall not want; 
&lt;br&gt;
He lets me apply quick refactors. 
&lt;br&gt;
He leads me to errors before compile; 
&lt;br&gt;
He cleans up my code. 
&lt;br&gt;
He navigates me in paths of inheritance 
&lt;br&gt;
for each namespace. 
&lt;/p&gt;
&lt;p&gt;
Even though I strive to remove cruft 
&lt;br&gt;
of the brownfield app, 
&lt;br&gt;
I fear no error; 
&lt;br&gt;
for You are in my IDE; 
&lt;br&gt;
Your red and Your green unit tests, they comfort me. 
&lt;/p&gt;
&lt;p&gt;
Surely correctness and maintainability shall follow me 
&lt;br&gt;
all the deployments of my app; 
&lt;br&gt;
and I shall dwell favorably in the thoughts of my 
&lt;br&gt;
Users forever. 
&lt;/p&gt;
&lt;p&gt;
&lt;em&gt;Sum(23)&lt;/em&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=81052414-02a8-471b-a1ea-6797594e24ba" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,81052414-02a8-471b-a1ea-6797594e24ba.aspx</comments>
      <category>humor</category>
      <category>resharper</category>
    </item>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=574b98b8-78fe-4d01-ae5e-bb3aace5e08e</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,574b98b8-78fe-4d01-ae5e-bb3aace5e08e.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,574b98b8-78fe-4d01-ae5e-bb3aace5e08e.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=574b98b8-78fe-4d01-ae5e-bb3aace5e08e</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This last week I gave two presentations at <a href="http://codestock.org/">CodeStock
2010</a>.  Thanks to everyone attended my sessions, hope you got something out
of them, and thanks to the <a href="http://www.vinull.com/">CodeStock organizers</a> for
all your hard work.  Here’s some content from the presentations:
</p>
        <div style="padding: 0px; margin: 0px; display: inline; float: none;" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:281044b0-3397-444d-85f3-322f47833d4c" class="wlWriterEditableSmartContent">
          <p>
            <a href="http://popcyclical.com/content/binary/images/CodeStock2010_A334/ParallelComputing_VS2010.pptx">Parallel
Computing in .NET 4 and VS 2010 - Presentation</a>
            <br />
            <a href="http://popcyclical.com/content/binary/images/CodeStock2010_A334/ParallelComputing_VS2010_code.zip">Parallel
Computing in .NET 4 and VS 2010 - Code</a>
          </p>
        </div>
        <p>
        </p>
        <div style="padding: 0px; margin: 0px; display: inline; float: none;" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:7829df64-f4ae-4cf2-87a8-4344219024a0" class="wlWriterEditableSmartContent">
          <p>
            <a href="http://popcyclical.com/content/binary/images/CodeStock2010_A334/Intro_To_PowerShell.pptx">Introduction
to Windows PowerShell - Presentation</a>
            <br />
            <a href="http://popcyclical.com/content/binary/images/CodeStock2010_A334/Intro_To_PowerShell_code.zip">Introduction
to Windows PowerShell - Code</a>
          </p>
        </div>
        <p>
        </p>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=574b98b8-78fe-4d01-ae5e-bb3aace5e08e" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>CodeStock 2010</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,574b98b8-78fe-4d01-ae5e-bb3aace5e08e.aspx</guid>
      <link>http://popcyclical.com/2010/06/28/CodeStock2010.aspx</link>
      <pubDate>Mon, 28 Jun 2010 00:21:01 GMT</pubDate>
      <description>&lt;p&gt;
This last week I gave two presentations at &lt;a href="http://codestock.org/"&gt;CodeStock
2010&lt;/a&gt;.&amp;nbsp; Thanks to everyone attended my sessions, hope you got something out
of them, and thanks to the &lt;a href="http://www.vinull.com/"&gt;CodeStock organizers&lt;/a&gt; for
all your hard work.&amp;nbsp; Here’s some content from the presentations:
&lt;/p&gt;
&lt;div style="padding: 0px; margin: 0px; display: inline; float: none;" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:281044b0-3397-444d-85f3-322f47833d4c" class="wlWriterEditableSmartContent"&gt;
&lt;p&gt;
&lt;a href="http://popcyclical.com/content/binary/images/CodeStock2010_A334/ParallelComputing_VS2010.pptx"&gt;Parallel
Computing in .NET 4 and VS 2010 - Presentation&lt;/a&gt;
&lt;br&gt;
&lt;a href="http://popcyclical.com/content/binary/images/CodeStock2010_A334/ParallelComputing_VS2010_code.zip"&gt;Parallel
Computing in .NET 4 and VS 2010 - Code&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;div style="padding: 0px; margin: 0px; display: inline; float: none;" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:7829df64-f4ae-4cf2-87a8-4344219024a0" class="wlWriterEditableSmartContent"&gt;
&lt;p&gt;
&lt;a href="http://popcyclical.com/content/binary/images/CodeStock2010_A334/Intro_To_PowerShell.pptx"&gt;Introduction
to Windows PowerShell - Presentation&lt;/a&gt;
&lt;br&gt;
&lt;a href="http://popcyclical.com/content/binary/images/CodeStock2010_A334/Intro_To_PowerShell_code.zip"&gt;Introduction
to Windows PowerShell - Code&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=574b98b8-78fe-4d01-ae5e-bb3aace5e08e" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,574b98b8-78fe-4d01-ae5e-bb3aace5e08e.aspx</comments>
      <category>codestock</category>
      <category>conference</category>
    </item>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=d0f44b48-8e48-4abc-a317-20fe798ae219</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,d0f44b48-8e48-4abc-a317-20fe798ae219.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,d0f44b48-8e48-4abc-a317-20fe798ae219.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=d0f44b48-8e48-4abc-a317-20fe798ae219</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <img style="display: inline" title="Double face palm" alt="Double face palm" align="right" src="http://suptg.thisisnotatrueending.com/archive/2911771/images/1225644751859.jpg" width="240" height="180" />
        <p>
Digging around in some code circa 6 months ago I discovered a method that I had scrounged
from the web and, in my apparent haste at the time, had not build any unit tests. 
It was less than 20 lines of code doing some simple array manipulation – and it was
from a pretty decent site, so it seemed pretty safe.  It’s the weekend so I thought,
hey, time to plug that gap!  I started with some simple cases and soon realized
that one of the execution paths was just … well, <em>plain wrong.</em></p>
        <p>
Luckily, that behavior wasn’t being used anywhere in my project (yet!), but still,
it was essentially a land mine waiting for someone to trip it.  My first reaction
was “shame on them for posting that without testing it!”  Of course, this code
didn’t end up in my project because of the author.  It was I who blindly accepted
and given it the “it’s from the internet!”-stamp-of-approval.
</p>
        <p>
Lessons learned today:<a href="http://popcyclical.com/content/binary/images/fd79eac90e05_13202/itsfromtheinternet.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="itsfromtheinternet" border="0" alt="itsfromtheinternet" align="right" src="http://popcyclical.com/content/binary/images/fd79eac90e05_13202/itsfromtheinternet_thumb.png" width="120" height="120" /></a></p>
        <ul>
          <li>
Trust is earned, not given.</li>
          <li>
Source code becomes trusted by-way-of thorough unit and functional testing.</li>
          <li>
Do not trust untested code from the internet.</li>
          <li>
Do not trust untested code from your own keyboard even more so – at least on the internet
it’s likely that someone else has reviewed it.</li>
        </ul>
        <p>
I’ve written the author a friendly note with a simple fix – it’s better to diffuse
that bomb than let it get somebody else!
</p>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=d0f44b48-8e48-4abc-a317-20fe798ae219" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>Trust Issues with Source Code</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,d0f44b48-8e48-4abc-a317-20fe798ae219.aspx</guid>
      <link>http://popcyclical.com/2010/05/23/TrustIssuesWithSourceCode.aspx</link>
      <pubDate>Sun, 23 May 2010 02:51:48 GMT</pubDate>
      <description>&lt;img style="display: inline" title="Double face palm" alt="Double face palm" align="right" src="http://suptg.thisisnotatrueending.com/archive/2911771/images/1225644751859.jpg" width="240" height="180"&gt; 
&lt;p&gt;
Digging around in some code circa 6 months ago I discovered a method that I had scrounged
from the web and, in my apparent haste at the time, had not build any unit tests.&amp;nbsp;
It was less than 20 lines of code doing some simple array manipulation – and it was
from a pretty decent site, so it seemed pretty safe.&amp;nbsp; It’s the weekend so I thought,
hey, time to plug that gap!&amp;nbsp; I started with some simple cases and soon realized
that one of the execution paths was just … well, &lt;em&gt;plain wrong.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
Luckily, that behavior wasn’t being used anywhere in my project (yet!), but still,
it was essentially a land mine waiting for someone to trip it.&amp;nbsp; My first reaction
was “shame on them for posting that without testing it!”&amp;nbsp; Of course, this code
didn’t end up in my project because of the author.&amp;nbsp; It was I who blindly accepted
and given it the “it’s from the internet!”-stamp-of-approval.
&lt;/p&gt;
&lt;p&gt;
Lessons learned today:&lt;a href="http://popcyclical.com/content/binary/images/fd79eac90e05_13202/itsfromtheinternet.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="itsfromtheinternet" border="0" alt="itsfromtheinternet" align="right" src="http://popcyclical.com/content/binary/images/fd79eac90e05_13202/itsfromtheinternet_thumb.png" width="120" height="120"&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Trust is earned, not given.&lt;/li&gt;
&lt;li&gt;
Source code becomes trusted by-way-of thorough unit and functional testing.&lt;/li&gt;
&lt;li&gt;
Do not trust untested code from the internet.&lt;/li&gt;
&lt;li&gt;
Do not trust untested code from your own keyboard even more so – at least on the internet
it’s likely that someone else has reviewed it.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
I’ve written the author a friendly note with a simple fix – it’s better to diffuse
that bomb than let it get somebody else!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=d0f44b48-8e48-4abc-a317-20fe798ae219" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,d0f44b48-8e48-4abc-a317-20fe798ae219.aspx</comments>
      <category>testing</category>
    </item>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=86f1449a-8d4c-4b00-892d-7c93f655b879</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,86f1449a-8d4c-4b00-892d-7c93f655b879.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,86f1449a-8d4c-4b00-892d-7c93f655b879.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=86f1449a-8d4c-4b00-892d-7c93f655b879</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I’m feeling a bit guilty about some code I wrote:
</p>
        <pre>
          <code>using (new OperationTimer("MyOperation", this)) { // ... complete operation
}</code>
        </pre>
        <p>
This innocent looking C# snippet is hiding a tricky secret - the <code>using</code> statement
is being misused (no pun intended).  The <a href="http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx">documentation
defines the intended usage clearly</a>:
</p>
        <dl>
          <dt>using Statement 
<dd>
Defines a scope, outside of which an object or objects will be disposed.</dd></dt>
        </dl>
        <p>
The problem?  The notion of “object disposal” is being hijacked!  In your
garden variety <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx"><code>IDisposable</code></a> implementation,
you’d be dealing with an <a href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">external
resource that needs to be released</a> before the object can be removed from memory. 
Instead, I’m using it to time a block of code like so:
</p>
        <pre>
          <code>class OperationTimer : IDisposable { private readonly string _operationName;
private readonly ITimable _obj; private readonly Stopwatch _stopwatch; public OperationTimer(string
operationName, ITimable obj) { _operationName = operationName; _obj = obj; _stopwatch
= new Stopwatch(); _stopwatch.Start(); } public void Dispose() { _stopwatch.Stop();
_obj.OnOperationCompleted(_operationName, _stopwatch.Elapsed); } }</code>
        </pre>
        <p>
The constructor starts a timer and the <code>Dispose()</code> method stops it and
reports the elapsed time.  (<em>aside: if you’re interested in how I’m using
the timer, check out my previous article </em><a href="http://popcyclical.com/2010/03/21/SimplifiedPerformanceCountersInNET.aspx"><em>Simplified
Performance Counters</em></a>) There are certainly other ways to accomplish this same
behavior, but they lack the elegance of a neatly scoped code block.  It’s arguably
an acceptable way to repurpose the language.  In fact, the ASP.NET MVC authors
saw fit to use it in a similar fashion with the <a href="http://msdn.microsoft.com/en-us/library/dd410596.aspx">BeginForm
helper</a>.  The only “resource” it disposes of is to render a closing <code>&lt;/form&gt;</code> tag.
</p>
        <p>
My question is: <strong>When does repurposing language constructs turn from “acceptable
language use” to a “dirty trick”, or worse, “illegible line noise”</strong>?
</p>
        <p>
It seems like a slippery slope.  One instance that I don’t care for is controlling
execution flow by-way-of logical operator precedence in most C-like languages:
</p>
        <pre>
          <code>expression1 &amp;&amp; expression2 || expression3</code>
        </pre>
        <p>
Which is equivalent to:
</p>
        <pre>
          <code>if (expression1) expression2 else expression3</code>
        </pre>
        <p>
This takes advantage of the order of evaluation in a logical statement – it is assumed
(correctly) that <code>expression2</code> will never be evaluated if <code>expression1</code> is
evaluated as false, and instead, <code>expression3</code> will get to run.  Likewise,
if the first two evaluate to true, the truth value is known for the statement and <code>expression3</code> is
never evaluated. This is clearly not the intended usage which the language designers
had in mind, but it works, and it saves any keywords from being written.
</p>
        <p>
Some truly beautiful code has been written by way of hijacking the language. 
For instance, <a href="http://www.cise.ufl.edu/~manuel/obfuscate/pi.c">here’s a program
that will calculate the value of pi using an ascii circle</a>.  Truly neat -
but also completely useless from a software development standpoint.
</p>
        <p>
What do you think?  Should I just get over my guilt about repurposing <code>IDisposable</code>? 
Or, should I be true to the original intent of the language and find another way?
</p>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=86f1449a-8d4c-4b00-892d-7c93f655b879" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>Programming Language Misuse</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,86f1449a-8d4c-4b00-892d-7c93f655b879.aspx</guid>
      <link>http://popcyclical.com/2010/03/24/ProgrammingLanguageMisuse.aspx</link>
      <pubDate>Wed, 24 Mar 2010 01:06:11 GMT</pubDate>
      <description>&lt;p&gt;
I’m feeling a bit guilty about some code I wrote:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using (new OperationTimer("MyOperation", this)) { // ... complete operation
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
This innocent looking C# snippet is hiding a tricky secret - the &lt;code&gt;using&lt;/code&gt; statement
is being misused (no pun intended).&amp;nbsp; The &lt;a href="http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx"&gt;documentation
defines the intended usage clearly&lt;/a&gt;:
&lt;/p&gt;
&lt;dl&gt;
&lt;dt&gt;using Statement 
&lt;dd&gt;
Defines a scope, outside of which an object or objects will be disposed.&lt;/dd&gt;
&lt;/dl&gt;
&lt;p&gt;
The problem?&amp;nbsp; The notion of “object disposal” is being hijacked!&amp;nbsp; In your
garden variety &lt;a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx"&gt;&lt;code&gt;IDisposable&lt;/code&gt;&lt;/a&gt; implementation,
you’d be dealing with an &lt;a href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx"&gt;external
resource that needs to be released&lt;/a&gt; before the object can be removed from memory.&amp;nbsp;
Instead, I’m using it to time a block of code like so:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class OperationTimer : IDisposable { private readonly string _operationName;
private readonly ITimable _obj; private readonly Stopwatch _stopwatch; public OperationTimer(string
operationName, ITimable obj) { _operationName = operationName; _obj = obj; _stopwatch
= new Stopwatch(); _stopwatch.Start(); } public void Dispose() { _stopwatch.Stop();
_obj.OnOperationCompleted(_operationName, _stopwatch.Elapsed); } }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
The constructor starts a timer and the &lt;code&gt;Dispose()&lt;/code&gt; method stops it and
reports the elapsed time.&amp;nbsp; (&lt;em&gt;aside: if you’re interested in how I’m using
the timer, check out my previous article &lt;/em&gt;&lt;a href="http://popcyclical.com/2010/03/21/SimplifiedPerformanceCountersInNET.aspx"&gt;&lt;em&gt;Simplified
Performance Counters&lt;/em&gt;&lt;/a&gt;) There are certainly other ways to accomplish this same
behavior, but they lack the elegance of a neatly scoped code block.&amp;nbsp; It’s arguably
an acceptable way to repurpose the language.&amp;nbsp; In fact, the ASP.NET MVC authors
saw fit to use it in a similar fashion with the &lt;a href="http://msdn.microsoft.com/en-us/library/dd410596.aspx"&gt;BeginForm
helper&lt;/a&gt;.&amp;nbsp; The only “resource” it disposes of is to render a closing &lt;code&gt;&amp;lt;/form&amp;gt;&lt;/code&gt; tag.
&lt;/p&gt;
&lt;p&gt;
My question is: &lt;strong&gt;When does repurposing language constructs turn from “acceptable
language use” to a “dirty trick”, or worse, “illegible line noise”&lt;/strong&gt;?
&lt;/p&gt;
&lt;p&gt;
It seems like a slippery slope.&amp;nbsp; One instance that I don’t care for is controlling
execution flow by-way-of logical operator precedence in most C-like languages:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;expression1 &amp;amp;&amp;amp; expression2 || expression3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
Which is equivalent to:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;if (expression1) expression2 else expression3&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
This takes advantage of the order of evaluation in a logical statement – it is assumed
(correctly) that &lt;code&gt;expression2&lt;/code&gt; will never be evaluated if &lt;code&gt;expression1&lt;/code&gt; is
evaluated as false, and instead, &lt;code&gt;expression3&lt;/code&gt; will get to run.&amp;nbsp; Likewise,
if the first two evaluate to true, the truth value is known for the statement and &lt;code&gt;expression3&lt;/code&gt; is
never evaluated. This is clearly not the intended usage which the language designers
had in mind, but it works, and it saves any keywords from being written.
&lt;/p&gt;
&lt;p&gt;
Some truly beautiful code has been written by way of hijacking the language.&amp;nbsp;
For instance, &lt;a href="http://www.cise.ufl.edu/~manuel/obfuscate/pi.c"&gt;here’s a program
that will calculate the value of pi using an ascii circle&lt;/a&gt;.&amp;nbsp; Truly neat -
but also completely useless from a software development standpoint.
&lt;/p&gt;
&lt;p&gt;
What do you think?&amp;nbsp; Should I just get over my guilt about repurposing &lt;code&gt;IDisposable&lt;/code&gt;?&amp;nbsp;
Or, should I be true to the original intent of the language and find another way?
&lt;/p&gt;
&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=86f1449a-8d4c-4b00-892d-7c93f655b879" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,86f1449a-8d4c-4b00-892d-7c93f655b879.aspx</comments>
      <category>c#</category>
      <category>language</category>
    </item>
    <item>
      <trackback:ping>http://popcyclical.com/Trackback.aspx?guid=80bb80dc-6a5a-4390-b96c-6fa4ecf66fa4</trackback:ping>
      <pingback:server>http://popcyclical.com/pingback.aspx</pingback:server>
      <pingback:target>http://popcyclical.com/PermaLink,guid,80bb80dc-6a5a-4390-b96c-6fa4ecf66fa4.aspx</pingback:target>
      <dc:creator>James Kolpack</dc:creator>
      <wfw:comment>http://popcyclical.com/CommentView,guid,80bb80dc-6a5a-4390-b96c-6fa4ecf66fa4.aspx</wfw:comment>
      <wfw:commentRss>http://popcyclical.com/SyndicationService.asmx/GetEntryCommentsRss?guid=80bb80dc-6a5a-4390-b96c-6fa4ecf66fa4</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I just posted an article on <a href="http://www.codeproject.com">CodeProject</a> about
a generalized code block which can be used in a common scenario for simple performance
benchmarking.  Check out <a href="http://www.codeproject.com/KB/dotnet/simpleperfcounters.aspx">"Simplified
Performance Counters for Timed Operations" here</a>…
</p>
        <p>
          <a href="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_AddCounters.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="OperationPerformanceCounter_AddCounters" border="0" alt="OperationPerformanceCounter_AddCounters" src="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_AddCounters_thumb.png" width="244" height="219" />
          </a>
          <a href="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_OperationsPerSecond.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="OperationPerformanceCounter_OperationsPerSecond" border="0" alt="OperationPerformanceCounter_OperationsPerSecond" align="left" src="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_OperationsPerSecond_thumb.png" width="244" height="86" />
          </a> <a href="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_AverageDuration.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="OperationPerformanceCounter_AverageDuration" border="0" alt="OperationPerformanceCounter_AverageDuration" src="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_AverageDuration_thumb.png" width="244" height="140" /></a></p>
        <img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=80bb80dc-6a5a-4390-b96c-6fa4ecf66fa4" />
        <br />
        <hr />
        <a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none">CodeProject</a>
      </body>
      <title>Simplified Performance Counters in .NET</title>
      <guid isPermaLink="false">http://popcyclical.com/PermaLink,guid,80bb80dc-6a5a-4390-b96c-6fa4ecf66fa4.aspx</guid>
      <link>http://popcyclical.com/2010/03/21/SimplifiedPerformanceCountersInNET.aspx</link>
      <pubDate>Sun, 21 Mar 2010 02:00:54 GMT</pubDate>
      <description>&lt;p&gt;
I just posted an article on &lt;a href="http://www.codeproject.com"&gt;CodeProject&lt;/a&gt; about
a generalized code block which can be used in a common scenario for simple performance
benchmarking.&amp;nbsp; Check out &lt;a href="http://www.codeproject.com/KB/dotnet/simpleperfcounters.aspx"&gt;"Simplified
Performance Counters for Timed Operations" here&lt;/a&gt;…
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_AddCounters.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="OperationPerformanceCounter_AddCounters" border="0" alt="OperationPerformanceCounter_AddCounters" src="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_AddCounters_thumb.png" width="244" height="219"&gt;&lt;/a&gt; &lt;a href="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_OperationsPerSecond.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="OperationPerformanceCounter_OperationsPerSecond" border="0" alt="OperationPerformanceCounter_OperationsPerSecond" align="left" src="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_OperationsPerSecond_thumb.png" width="244" height="86"&gt;&lt;/a&gt;&amp;nbsp;&lt;a href="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_AverageDuration.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="OperationPerformanceCounter_AverageDuration" border="0" alt="OperationPerformanceCounter_AverageDuration" src="http://popcyclical.com/content/binary/images/SimplifiedPerformanceCountersin.NET_E293/OperationPerformanceCounter_AverageDuration_thumb.png" width="244" height="140"&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://popcyclical.com/aggbug.ashx?id=80bb80dc-6a5a-4390-b96c-6fa4ecf66fa4" /&gt;
&lt;br /&gt;
&lt;hr /&gt;
&lt;a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=1252729" rel="tag" style="display:none"&gt;CodeProject&lt;/a&gt;</description>
      <comments>http://popcyclical.com/CommentView,guid,80bb80dc-6a5a-4390-b96c-6fa4ecf66fa4.aspx</comments>
      <category>benchmark</category>
      <category>diagnostics</category>
    </item>
  </channel>
</rss>