Programming When Clarity Counts May 5th, 2009
Patrick Stein

In my previous post, I wrote some code in Perl because I wanted the code to be clear and obvious. Wait? What? Who uses Perl when they want clarity?

Perl

I admit: I was surprised myself. Seriously, I tried several other languages first. Let’s just focus on the first loop here. Here’s the Perl again for reference:

my $total = 0.0;
foreach my $item ( @list_of_items ) {
    $total += weight( $item );
}

Objective C

The actual code that I was attempting to explain was in Objective C with the NeXTStep foundation classes. I couldn’t imagine that anyone would want to try to understand it:

double total = 0.0;
NSEnumerator* ee = [itemList objectEnumerator];
Item* item;
while ( ( item = (Item*)[ee nextObject] ) != nil ) {
    total += [item weight];
}

C

My first attempt for the article was to write it in C using an array of items.

double total = 0.0;
unsigned int ii;
for ( ii = 0; ii < itemCount; ++ii ) {
    total += weight( itemArray[ ii ] );
}

That’s not too terrible. There is, however, a great deal of syntax and code devoted to handling the array including an extra variable to track its length. Beyond that, the loop counter is of little use to someone trying to understand the concept.

C++

My next go was C++. My hope was that iterators would make the looping less painful. C++ iterators, however, are the very model of pain.

double total = 0.0;
std::list< Item* >::const_iterator it;
for ( it = itemList.begin(); it != itemList.end(); ++it ) {
    total += weight( *it );
}

This requires the reader to wade through a syntactic thicket to get the iterator into the picture at all. It also requires a certain comfort with pointers that one wouldn’t have coming from another language.

Java

My next attempt was Java. I hate Java. It may not be terrible for this code with the new looping constructs that came in Java 1.5. Alas, I quit coding it before I made it through this first loop.

Lisp

Of course, I wanted to code this in Lisp:

(let ((total (reduce #'+ list-of-items :key #'weight)))
   ...)

That would be perfectly clear to someone who has used Lisp or Scheme. Alas, not everyone has.

So… Perl…

If you want to write the Perl code, you have to understand the difference between scalars and arrays. To read the code, however, you don’t have to grok that distinction to see what’s going on. I didn’t try it in Python. Maybe it would be clear to a wider audience. I may have to try it next time.

How to Make a Weighted Random Choice May 5th, 2009
Patrick Stein

Today seemed like a dull day at the keyboard. I beat my head against Objective C a lot. And, I implemented a weighted random choice which I have done a thousand times before. Dull, right?

I needed a weighted random choice in two different places, and I implemented it differently in each place. Weird, right? Even weirder, I think I did the right thing in each place.

Picking a card from a deck

In the first case, I needed to choose a flash card from a deck. I want to favor cards that have given the player trouble in the past. I zip through the list once to sum up the weights. Then, I pick a random number greater or equal to zero and less than the sum of the weights. Then, I run through the list again summing the weights until my running sum exceeds my random number. (Here in Perl, um, for clarity?):

my $total = 0.0;
foreach my $item ( @list_of_items ) {
    $total += weight( $item );
}

my $thresh = rand( $total );
my $found;

foreach my $item ( @list_of_items ) {
    $thresh -= weight( $item );
    if ( $thresh < 0.0 ) {
        $found = $item;
        last;
    }
}

This requires that the weight() of a given item remains constant for the duration of the function. The weight() can change between choices, however. If the weight() will remain constant for large portions of the program then you can cache the total and only bother with the second half of the loop.

Choosing a letter of the alphabet

In a different portion of the program, I need to make random letter tiles. I feel like there should be more E‘s than Q‘s. I also want to leave a pathway to use the same artwork for different languages. Because of all of this, I opted to have the weights to come in from a file.

My data file is JSON encoded. I could, I suppose, do something like this (given the English letter frequencies):

{
    "english" : {
        "A": 8.167,
        "B": 1.492,
        "C": 2.782,
        ...
    }
}

But, that hurts to even think about. Instead, I opted to round them off to integer proportions. Then, I could just do this:

{
    "english": "AAAAAAAABBCCC..."
}

Now, making a random choice simply involves selecting one character from the string.

Study Clifford Algebras with Me May 4th, 2009
Patrick Stein

I want to learn more about Clifford Algebras. I want you to join me on the journey.

I just sent an email to Cambridge University Press asking permission to use the book Clifford Algebras and the Classical Groups by Ian R. Porteous as the outline and springboard for a long series of posts about Clifford Algebras.

More details once they respond….

Exponential Spirals for Game Effects May 4th, 2009
Patrick Stein

In earlier posts, I mentioned finding polynomials, riffing off of damped harmonic motion, and then hitting on exponential spirals all trying to come up with a nice looking way to snap game tiles back into place when they are released. I want them to overshoot and then settle into place rather than snap directly into their spot.

The Basic Spiral

I am talking about a simple spiral of the form:

\theta(t) = Kt
r(t) = \alpha\left(Kt\right)^{n}
for some integer n.

That would be an equation for a spiral that starts at the origin and heads outward as t increases. For my application though, I want to end at the origin so I need to substitute 1-t in for t.

\theta(t) = K(1-t)
r(t) = \alpha\left(K(1-t)\right)^{n}

The math is also going to work out slightly better if I use n-2 in place of n in the above equations:

\theta(t) = K(1-t)
r(t) = \alpha\left(K(1-t)\right)^{n-2}

I don’t want the piece to spiral into place when released though. So, really, I am concerned with just the x coordinate from the above equations:

x(t) = r(t) \cos \theta(t) = \alpha K^{n-2} (1-t)^{n-2} \cos \left(K\left(1-t\right)\right)

To normalize everything, I am going to let \alpha = K^{2-n}. And, since I want my interpolation value to go from zero to one instead of one to zero, I am again going to subtract this all from one:

x(t) = 1 -  (1-t)^{n-2} \cos \left(K\left(1-t\right)\right)

Read the rest of this entry ⇒

A Eureka Moment May 1st, 2009
Patrick Stein

I was pondering the Phony Physics again as I set to work on my iPhone app.

In the previous post, I twiddled the equations for damped spring motion until I found something visually pleasing. Last night, I went back to the drawing (a.k.a. white) board.

What if I used an exponential spiral (parameterized by arc length). Then, I could easily adjust the number of times it bounces back and forth. I could use a spiral like r(t) = \alpha K (1-t)^n and \theta(t) = K(1-t) where K is some multiple of 2\pi. Then, I could walk along the spiral getting to the origin when t = 1 going around the origin \frac{K}{2\pi} times in the process. If I follow the curve at a fixed rate, then I guarantee that my oscillations will pick up speed as I approach the origin.

Rather than have it spiral into the center, I am just using the x-coordinate of the spiral as my new t value to interpolate with. I like the effect for the most part. It overshoots a little bit far on the first oscillation. I may tweak it some more before it’s all over. For now though, I am sticking with it.

I will post some graphs soon.

Updates In Email

Email:

l