Programmer sestina

I have taken up Geoffrey’s challenge on writing a sestina. Man it’s hard! If you love seeking patterns in things, then see if you can figure out what a sestina is. If you’re stuck, well, here’s a hint.

Of course, I cheated a bit, since we all know hit songs are nonsense lyrics strung together. So if you don’t understand any line, it’s because I ran out of inspiration and just plopped something to fill the void.

The programmer sestina

Just like the life giving warmth of the sun
You can create a better world through your code
Even something as simple and mundane as water
This element of old courses the veins of a tree
With earth and air, ancient elements the other two
They fuse together, becoming a beautiful force

As a programmer, you wield tremendous force
You are not as solitary as the sun
Close by you’ll always find a friend or two
Spurring one another to write better code
Solving the very root of the problem tree
And cleanse the ultimate source of foul water

Learn to calm your mind, like placid lake water
Only to turn in a moment’s notice to a tidal force
Be unyielding with the will to grow of a tree
Reaching for greatness, reaching skywards for the sun
Technology advances with the rising quality of code
Or retards with the bad, these consequences just two

Counting in numbers, arithmetic base two
Should be easy and fun, like playing in water
If ever you find it hard to produce code
‘Cause of meetings, deadlines, pressure and force
Just look out the window, to feel the sun
And listen to the rustling leaves of a tree

Many roles you fill, more than leaves on a tree
You wish there’re more of you, like at least two
Trapped in dingy cubicles away from the sun
With no coffee, no tea, or even cooler water
You buckle down under corporate bureaucratic force
Churning out line after line of uninteresting code

Programmers solve puzzles and enigmatic code
Or use the concept of graph nodes in a tree
Or implement the formula of gravitational force
You’re unique, like the only even prime that’s two
You’re adaptable, filling needs and voids like water
So go out there and shine more brightly than the sun

Climb a tree and reach for the sun
Smell the brine water and dig into your force
You’re better than two extreme programmers writing code

Math is good

According to this article,

mathematics help students to develop a quantitative sense as well as a strong analytical and logical reasoning skills, which will assist them in acquiring new knowledge, be innovative and take calculated risks with confidence.

Strong analytical and logical reasoning skills? Isn’t that what you need when programming?

Then in another article,

most of the major problems we face are math and science problems

Time to brush up on some algebra!

Fibonacci sequence and Golden Ratio

Baby rabbits by Wee Gan Peng @iStockphoto

I haven’t written a math-related article in a while, so in this article, I’ll tell you about the Fibonacci sequence, the golden ratio and some associated program code.

Say you’re given this math formula, and told to find what the nth term is.
F(n) = F(n-1) + F(n-2)
where F(1) = F(2) = 1

Wow, initial conditions are given, a formula is given. Functions! In fact, use recursive functions! That was easy to code, wasn’t it?

What if you’re given this sequence of numbers and told to find what the nth term is?
1,1,2,3,5,8,13,21 …

You would get exactly the same answer for both questions. Notice that each subsequent number is a sum of the previous two numbers (except the first two in the sequence). Once you find the pattern, you can make use of simple loops instead of recursive functions. Generally speaking, recursive functions are slower, and you would not have known the simpler loop solution if you hadn’t analysed the problem first.

Of course, if you knew the numbers form the Fibonacci sequence, you wouldn’t have much of a problem in the first place, would you? You might have heard of it in Da Vinci Code, where the sequence was used to decipher a password number.

Now, the interesting thing about this sequence is that Nature uses it. I haven’t personally verified this, but sunflowers, pineapples and daisies exhibit the use. If you count the number of bumps on them going to the left, and the number of bumps to the right, you’ll find that the numbers are right next to each other in the Fibonacci sequence. For example, sunflowers have 34 spirals to the left and 55 to the right.

The rabbits, man do they breed!

There’s actually a story about how the Fibonacci sequence came about. You might have guessed that Fibonacci is the name of a mathematician. Anyway, the story goes like this. Suppose there are 2 rabbits, one male and one female. Each month, they produce two rabbits, again, one male and one female. The baby rabbits take one month to grow, and become sexually reproductive in their second month. In this manner, how many rabbits are there at the end of 12 months?

In the first month, there are 2.
At the end of the second month, there’s 4 (2 original, 2 babies).
At the end of the third month, there’s 6 (2 original, 2 from 2nd month, 2 babies from original).

At the end of the fourth month, there’s the original 2, the 2 from 2nd month, the 2 from 3rd month, 2 babies from the original 2, and 2 babies from the 2 of the 2nd month. Total rabbits: 10.

Just typing this out is confusing, but you can see a pattern emerging.
2, 4, 6, 10 …
Each subsequent term is a sum of the previous two terms.

Oh yes, the number of rabbits in the 12th month is 466.

Some obvious assumptions are

  • Rabbits never die
  • Babies are always produced in a pair, one male and one female
  • Moral values are not considered (incest shmincest!)

The golden ratio

There is another interesting thing. The ratio of F(n+1)/F(n) approaches a limit as n goes to infinity, which is approximately 1.618. This number is known as the golden ratio, with other names such as golden mean, divine proportion and others. Other than its mathematical relevance, I know it to be important as an aesthetic factor.

A rectangle with its sides in this ratio is thought of as aesthetically pleasing. This probably influenced the manufacture of computer screens. You have your standard 4:3s (1.333:1), the 800×600, 1024×768 and others. There are also some who tried the square root 2 ratio, 1.414:1 in computer applications. Then there’s the 16:9 (1.777:1) aspect ratios.

What’s the purpose of these aspect ratios? To approach the golden ratio 1.618:1. Of course, with widescreens, this point is probably moot nowadays. Still, it makes for interesting contemplation.

Ok, let’s do some coding, calculating the nth term using a loop, which I’ve hardcoded as 20. I’ll leave it to you as an exercise to write it as a function. The golden ratio is calculated as well. The first 2 terms are skipped, because they are equal to 1 (initial conditions).

int i;
int current, previous, next;
double phi = 0;
current = previous = 1;
for (i = 2; i < 20; ++i)
{
    next = current + previous;
    previous = current;
    current = next;
    phi = (double)current/(double)previous;
    Console.WriteLine("Term {0,0:d2} = {1,0:d5}, Phi = {2,0:f8}", i + 1, current, phi);
}

Fairly simple. The point is to convert a problem into a program solution. The difficult part isn’t the original problem, nor is it about coding skills. It’s about translating a problem into a program that’s difficult.

There you have it. Math theory and supporting program code. Hope you enjoyed it.

Update: Commenter Patrick pointed out the existence of the closed-form expression of the Fibonacci numbers. Thanks Patrick!

Exploits of a mom

Here’s a comic strip I recently read. I can’t remember whose RSS feed I read it from (sorry!), but I Googled, and found the original source (I hope). Here’s the link: http://xkcd.com/327/

Shrunk a little to fit into the width. Click to enlarge.
Exploits of a mom

When I read it, I laughed and laughed. I did LOLs and nearly did an ROTF. So I shared it with my fellow colleagues. As expected, no reply. However, one fellow asked me what the joke was.

So I explained it to him, giggling and excitedly. Now I don’t know whether I’m happy that I explained the joke to him, or that I’m sad because I had to explain the joke to him. Seems like I’ve got some work to do about creating awareness on SQL injection and other security issues…

Repeatedly shooting hoops

Shoot the hoop by Matthew Porter @iStockphoto

I was walking around the arcade. Fighting games, 2D or 3D, were the rage once. Then there’s those dancing games, where you step to the beat on one of 4 floor panels. Then there’s driving simulations, where players strive for beautiful exit curve lines and cool looking drift moves.

I was walking around the arcade. One of my favourites is the shooting games. Time Crisis, House of Dead and recently Silent Hill. Why? Because they’re the ones with a story plot. And if the players are moderately good, I get to see the story unfold. If they don’t shoot at the screen to skip the cut scenes of course…

I was walking around the arcade. Recently, two arcade centres I frequent did some major shifting of their machines. Both pushed the same game machine type to the forefront, visible immediately upon entering.

This game machine was added quite a while ago, but from the rearrangement, I’m guessing it’s gaining popularity. And the arcades stack them side by side, 8 in a row. And the machine is one of the few that physically engages the player in the game.

It’s a basketball game machine.

Specifically, it’s a shoot-the-hoop game machine. There’s just enough space for one person to stand in front of it. What you do is simply, uh, shoot the hoop. Each machine has 6 basketballs, and at the start of the game, the basketballs roll downwards towards the player. I think an illustration is in order…
Basketball game machine side view
There’s a protruding panel that flips up and stops the basketballs from rolling down once the game ends. There’s also a metal grate to reduce the likelihood of basketballs bouncing out of the machine. Basketballs can bounce out very far if they hit the hoop at the correct angle…

I don’t know how many sets a player has in one game. Maybe 3, maybe more if there’s bonus sets. Anyway, each set lasts for 60 seconds. During those 60 seconds, the player simply try to score as many times as possible, throwing the ball and make it fall through the hoop. Each successful throw nets the player 2 points. During the last 15 seconds of each set, a successful throw is worth 3 points. If I understand it correctly, in the second and third set, the hoop will move from side to side, increasing the difficulty.

Why am I talking about this? Because I noticed a similarity among the good players. All of them had their eyes fixed on the hoop. Their hands just keep getting the balls in front of them and they just shoot. Their concentration is focused on the hoop, and they just keep shooting. And shooting. And shooting.

Basketball isn’t solely about shooting the hoop of course. There’s dribbling, there’s teamwork, there’s accurate passing. But this game machine allows you to practice the shooting, over and over again, in a very short amount of time.

I actually find watching the good players playing, rhythmically mesmerising. There’s something very elegant in the way they take up a basketball, hold it up, throw and score in one smooth motion. I’ve seen a player use both hands, as in right hand take up ball and throw. Then the left hand take another ball and throw. Left, right, left, right. How’s that for ambidexterity?

If you read this far, I appreciate your attention and time. And now for the crux of this entire story. If you find programming difficult, start small. Write small programs as proofs of concepts that you learn. Then write a lot of them. Write them in different ways. Rearrange code to test your understanding. Build on your understanding.

Say you just learned about arrays. Test your understanding. Write small programs iterating through them. Read values from them. Assign values to them. When you keep working with arrays, you get familiar with them. Then you get to the point where using them becomes natural to you. You know what you can and cannot do with them. Then you move on to another concept.

Programming is about putting together concepts and constructs. It’s when you’ve understood the basics, that you can think beyond them. That you can invent and write advanced software.

All software, great and small, are made up of the basic programming constructs. Variables, assignments, loops and more. All you need is practice. Practise writing code. It’s the same with learning a (human) language. The more you read and write it, the better you become at it.

The rapid repetition of just throwing basketballs and scoring, trains the player to become very good at it, in a very short amount of time. After one particular game, I checked a player’s scores. Close to 200 throws with 80 percent accuracy. That’s 200 throws in 3 sets, 180 seconds, which comes to about 1 throw per second. That’s fast. Not to mention tiring. Can you keep throwing basketballs non-stop for 3 minutes?

Becoming better at programming can mean just practising writing good code until it’s ingrained into you. Write more, write often and write small.