Squares, hexagons and distance

Most traditional board games use squares to segregate space.

Square terrain

Space is divided evenly. Lines are easy to draw. Everything is structured. Bliss.

Except that when you need to move to a diagonal square, you need to move 2 squares instead of √2 squares. Wait, a non-integer movement? That cannot be tracked!

Dungeons & Dragons 4th Edition (a tabletop RPG with physical positional tracking) state that a diagonal square movement costs the same as a perpendicular square movement. Meaning you just move 1 square to reach that diagonal square. This also has its problems.

For example, there’s a concept of push in D&D, where as long as the target being pushed is moved further away, it counts as a push. Bringing us to this situation:

Perpendicular push movement

I talked about this briefly on my other blog, but didn’t go into the math details. So the blue dot is you, the red dot is the enemy, and the brown dot is where the enemy is pushed to.

The distance between you and the enemy is (do the Pythagoras thing) 2√2 (approx 2.8284). The distance between you and the final position of the enemy is √10 (approx 3.1623). Sure √10 is greater than 2√2, so mathematically speaking, the enemy is moving away from you. But common sense is telling me otherwise, because the direction of the push emanates from you.

Anyway, to combat the shortcomings of the square terrain, there’s the hexagonal terrain.

Hexagonal terrain

Under this division of space, all adjacent spots are equidistant to your position. Well, it still has its problems. You still need 2 hexagons of movement to reach the first hexagon directly above you.

Hexagonal movement

So what’s the actual cost of movement? Let’s look at this extracted diagram:

Hexagonal movement calculation

Let h be half of the actual distance. Doing the Pythagoras thing again, we have
1^2 = h^2 + (1/2)^2
=> 1 = h^2 + 1/4
=> h^2 = 3/4
=> h = √3/2 (h is positive)

Therefore, the actual distance is 2h which is √3 (approx 1.7321). Not quite 2 hexagons, is it?

This is part of the reason why, when games are created on computers, that these limitations disappear. Because computers can do the distance calculations and tracking. You can move in any direction, for any amount of units of movement, as long as you do not hit anything.

And that is called collision detection.

Stuff I am doing lately

I had a tumultuous past month (or so).

My network adaptor died on me, and since my computer then was about 5 years old, I thought “Why not just get a new computer?” So I did.

Due to some personal reasons, I feel a bit worn out. So I’m putting that ebook project on hold for a while. Partly because I’m also channelling my energy to another blog. Please visit Honeybeech, where I tell stories, mainly about my Dungeons & Dragons gameplay adventures.

Rest assured that I’m still here. So I’ll be writing math and programming topics here at Polymath Programmer, and RPG/fantasy/fiction stuff over at Honeybeech.

Because even programmers need to eat (as in “eat properly”, despite whatever you’ve heard about pizzas and fizzy drinks), I’m writing an ebook as a D&D game supplement. It’s called Math Wizard (I know, it’s so “me”, right?), and the character’s powers are mostly based on math and science concepts.

Considering all my options, I believe I have a better chance at making “Math Wizard” work better than “Discipline and Deflection” (the original ebook project). I also believe the former can inspire more people and ignite their imagination and curiosity than the latter. I will still create both, and I’m just constrained by time and effort.

A friend also introduced me to a book store here in Singapore called BooksActually. They have a sister branch called “Polymath & Crust”. Awesome! They have the word “polymath” in it. I have to visit that book store.

Polymath & Crust

The store is located at No. 86 Club Street Singapore 069454, if you’re interested.
[Disclosure: I'm not paid by them. I even bought a book. See below.]

We went in, and it was a quaint little place, carrying books that you don’t see in major book stores. My friend bought himself a dictionary of symbols, and I bought a dictionary of mathematics.

Dictionary of Mathematics

Even their paper bag is interesting. I wonder what that interesting shape mean?

Polymath & Crust paper bag

Is math important to programming?

It depends.

Now that we’ve gotten the short answer out of the way, let’s discuss this further. Recently, Jeff Atwood asked Should Competent Programmers be “Mathematically Inclined”? I don’t get the need for the quotes, but never mind…

The summary of his article is that the problems involving math that most programmers deal with are the “balancing your checkbook” kind. Meaning simple math is required, meaning you don’t need to be a math whiz to solve that problem with programming. And I agree with him.

My work currently puts me in contact with a lot of numbers. As in quantities in the 10 digits range, with values also in the 10 digits range. And the finance and credit departments of my employer are very interested in those numbers…

Anyway, the manipulation of those numbers require very little math, despite their math origins. How hard can it be to sum up figures, do discrete prorating, calculate percentages or find out the price based on existing rates?

The initial reading of Jeff’s article made me feel indignant (goes off to check that I indeed write about math and programming). How dare he view math as frivolous to programming! How dare he reduce math to insignificance! (wipes spittle from mouth)

Then the cold hard truth of my professional programming experience knocked my senses back into place. I had to remember that the work I did back in university just wasn’t… useful (directly) to my present work. I worked with 3D, image rotations and optimising an airflow simulation. Not quite the business related programming I do now.

I still believe math is useful to programmers. Just as you should learn C, even if you don’t use C in your regular work. I’ll tell you how math and C are related in a bit, but first…

Math is elegant

I agree with Steve Yegge. They teach math all wrong in schools. This is despite his American background and my Singaporean background. I guess errant math education has no borders

The earlier parts of math education focus on calculations and memorisations. Oh, there are some proving questions (much to my distaste) alright, but there’s not a lot of them. In university, my math education started to take on a distinct shift; there were fewer numbers in the questions.

I remember there was this linear algebra tutorial. There were only 4 questions in it. I took a grand total of 4 hours to complete it. Even then, I didn’t fully answer the questions. It was proving this, or ransacking notes to find out which theorems were applicable, or wandering into higher dimensional linear spaces (I think I hated the professor at one point during my struggle). I think I even skipped 1 (or 2!) question. That’s how different the questions became.

With this shift, I found math to become more … elegant. Suddenly, plugging in numbers into calculation formulas aren’t important anymore. Even remembering proofs and theorems take backstage. Figuring out which method, proof or theorem to use to solve a question in the simplest manner is paramount.

I started to solve problems elegantly, be they math or programming.

And for me to find elegant solutions, I needed to think more. Much more. Sometimes this fails, and I end up with a less-than-ideal-elegance solution. But that’s ok. If I don’t aim for elegance, I’ll never reach it.

In my earlier stages of education, math was binary. Either my solution was right, or it was wrong. Later on, it was right. And there’s another solution that’s also right, and shorter. Or easier to understand. Math solutions became a little fuzzy.

What I’m saying is that although math isn’t directly useful to my programming, it certainly shaped the way I solve programming problems. Because programming solutions are also a little fuzzy.

Many programming solutions are sub-optimal. And they don’t need to be optimal. They already solve all normal occurring cases, and maybe the edge cases don’t matter that much. Or maybe there isn’t an optimal solution. In which case trying to find the optimal solution is a waste of time. So much for elegance.

So is math really important? I can’t say for you (despite writing an article on it), but C isn’t that important for programmers either.

Learning C makes you think

It’s sometimes hilarious to see Jeff and Joel argue about the importance of learning C. Joel does have a point. Learning C makes you think harder about solving programming problems (pointers and all). It doesn’t mean you’ll ever use any of the solutions (or C for that matter), but it trains your mind to think.

And in this respect, that’s what C and math are to a programmer. Learning both makes you think. You’ll think about just solving the problem. You’ll think about a more elegant solution. Maybe coming up with a less convoluted solution but eminently understandable by your fellow programmers.

But if you never go through the extremes of “slap messy but amazingly it works” and “elegant one liner but takes forever to understand”, then you might find it hard to find a happy in-between state. Because you just don’t know what’s possible.

“So is math important to programming?” an obvious exasperation in your question.

Well … it depends. On you.

Lament of an artist

I recently came upon a tweet by Kathy Sierra. Here it is:
Mathematician's Lament tweet from Kathy Sierra

So I went ahead and downloaded the PDF file and read it through. Man did it resonate! Here’s a quote that practically captured the essence:

Mathematics is an art
- Paul Lockhart

Lockhart was describing how the current education in America was eroding the sense of wonder, discovery and thrill of mathematics in children and young adults. First, go download his article Mathematician’s Lament (about 25 pages) and read at least the first and last few pages if you’re in a hurry.

I don’t know much about the American education system, but the way it’s described, it’s bad. And the Singapore education system (at least with regards to math) is similar (well, at least from what I remember when I was studying). The sense of discovery just wasn’t there.

When I was about ten (I think), my parents bought me an encyclopedia set, Childcraft. The first book I went for? The one on mathematics.

I gorged myself on the puzzles, stories, thought experiments in the book. For example, there was that crossing of river puzzle, with a farmer and a sheep and a wolf. There was a story excerpt of Flat World, where Points and Lines meet the 2 dimensional Squares and Pentagons. And there’s a “proof” of the non-existence of vampires. And … wait, what? You want to know the proof?

Ok, suppose vampires suck blood out of victims and the victims become vampires themselves. Suppose there’s only 1 vampire in the beginning. On the first night, he bites one person. By the next day, there are 2 vampires. 2nd night, each vampire bites another person. So there are 4 the next day. I’m sure you can see how this goes… at some point, the doubling vampire population simply overshot the entire world population. But we’re still here, aren’t we? Hence no vampires.

Of course, that proof goes out the window if vampires don’t need to bite every night… or if they can control who to turn into a vampire… ok, moving along…

Oh yes, with this encyclopedia in hand, I learnt about the fun parts of mathematics. I learnt about the magic numbers of 3, 4 and 5 forming a standard 3^2 + 4^2 = 5^2 Pythagorean triangle long before I actually knew what Pythagoras’ Theorem was. I read about how the ancient Greeks were racking their brains for how to get a right angle, and they used a length of rope with evenly spaced knots. They found that a triangle with sides of 3 knot length, 4 knot length and 5 knot length, created a right angle at one of the corners. That was fascinating.

There was also this section on Fibonacci numbers, and a story about rabbits. The algorithm behind the sequence was presented with an interesting back story of an expanding bunny population. I remember in university, my professor mentioned the sequence and I exclaimed, “Fibonacci sequence!”. And my friend, who’s sitting beside me, turned to me and asked, “You know about this?”. Really? A math university student who don’t know about Fibonacci sequences?

I don’t know about you, but for all the talk about Asians being better (at math) (here and here), I think most of us still don’t get to see math as an art, as something beautiful to contemplate. I started out seeing math as fun, then later on as something scientific and not-so-fun. And after my service in the military, I went to university, and suddenly it’s fun again. I guess it took me a fresh perspective to view math once more…

And I think programming is like math. No, I’m not bringing in the meta-blogging type of “This blog topic is something like that” and go off on some far out analogy. I mean programming, like math, requires one to see the abstract, manipulate pieces of information in the mind’s eye, come up with solutions in the ether, and then bring forth the solution into the world.

Right now if you ask me about math, like really hard core math, I’d probably stumble. Partly from a long disuse of the principles, but mostly because unconsciously, I’m trying to capture that sense of wonder again. That requires me to shed some undesirable shackles and discipline, and allow myself to not know everything on the topic. Math fun is back in vogue.

P.S. The next book in the Childcraft encyclopedia I pounced on? The one with stories. I guess I’m a sucker for fiction. *smile*

Math, culture and programming languages

Can a programmer’s background determine whether he’ll be a great programmer? By background, I mean his upbringing, the values learnt, his primary (and perhaps secondary) spoken/written language and so on.

I don’t know. However, I have arguments for and against the proposition. Let’s start with…

Learning to count

You think counting is easy? Apparently not. Recently I read a book, Outliers by Malcolm Gladwell. According to Gladwell, American children the age of four can, on average, count up to fifteen. Chinese children at that age can, on average, count up to forty.

His reasoning is that, the system of naming numbers is different in English and in Chinese.

For example, think about counting from twenty to thirty (I’m deliberately using the English form instead of the Arabic numerals to highlight the difference). You have twenty, twenty one, twenty two and so on till twenty nine and thirty. How about thirty to forty? Thirty, thirty one, thirty two and so on till thirty nine and forty.

Consider counting from ten to twenty. Ten, eleven, twelve, thirteen and so on till eighteen, nineteen and twenty. The pattern is different and irregular.

Before I show you the Chinese method of counting, let me show you the first 10 numbers, shown by the Arabic numeral, the English name and the (closest) Chinese pronunciation I can give:

1 one (yi, like in “yeast”)
2 two (er, like in “brighter”)
3 three (san, “sahn”)
4 four (si, do a short hissing sound with the s)
5 five (wu, “woo” and keep it short)
6 six (liu, “li” and “ou” as in “shoulder”, and string li-ou together quickly)
7 seven (qi, “cheese” without the s, and shorter in length)
8 eight (ba, as in “barter”)
9 nine (jiu, “gi” as in “gin” and “ou” as in “shoulder”. Like that of six.)
10 ten (shi, like that of four, with the h)

There are actually 4 tonal inflections for a Chinese character pronunciation, and we’ll ignore that for this discussion.

So to count in Chinese from ten to twenty, we have shi, shi yi, shi er, shi san, shi si, shi wu, shi liu, shi qi, shi ba, shi jiu, er shi. They are literally “ten”, “ten one”, “ten two”, “ten three” and so on till “ten nine” and “two ten”. There’s an implicit “one” in front of the “ten”, so it’s “one ten one” for eleven. For twenty three, it’s “er shi san”, or literally “two tens and three”.

Gladwell says this gives structure to the counting system, so children are able to grasp larger numbers quicker. The faster you can count to larger numbers, the more operations you can do on them. Additions, subtractions, summations and so on.

Ok, I’m not saying the Chinese number naming system is better than the English system. It’s just different. Gladwell says this difference also makes memorising short number sequences easier. For example, I can remember my Identification Card Number (equivalent to the Social Security Number in America) easier in Chinese than in English.

It explains why when someone asks for my phone number in English, I have a problem. Because I’m mentally translating my memory of the phone number from Chinese to English. Did you know it’s kinda hard to say out 8 digits in English while translating them from a Chinese memory? I can even mentally picture the numbers. It’s the speaking out that’s taking up mental processing time.

Gladwell also made a point about Cantonese (a Chinese dialect) pronunciation of numbers. So I tried saying out numbers in Cantonese (yes, I’m multilingual), and wow, it is easier to say and memorise! The Cantonese pronunciation of numbers are short in length, which makes it easier to spit them out *smile*

And the relation to programming? Programming is made up largely of counting and solutions formed from abstract ideas. When I first learned C, I was surprised that many fellow students had difficulty counting the number of iterations in say,

for (i=0; i<10; ++i)
{
	if (i>7) break;
	// do something
}

Counting and iterating leads to lists of data, or sets of data. In SQL, you can manipulate sets of data as if it’s one unit, abstracting away the fact that the data is actually iterated one by one. For example, you can select information from another data set, or a subquery as it’s known.

Of course, there are still some people who have difficulty visualising SQL data sets as one unit, hence their need to iterate over that one record by one record at a time, even when there’s no need. What does that tell you about these people?

Hard work is valued

Gladwell also made a point about culture. That successful people seem to grow up with a culture of valuing hard work. The ability to think on a problem long enough to come up with a solution.

He said something worth thinking about. There’s a educational researcher by the name of Erling Boe at the University of Pennsylvania. Boe says that one can know if a child will do well in math without asking that child a single math question.

The example in the book was a fictional Math Olympics. Before the test, there was a questionnaire to be filled in. There were tons of questions inside, none related to math. Boe asserts that a child who finishes that questionnaire will also do correspondingly just as well in the math test.

It’s a question of perseverance, the willingness to put one’s mind to work, even if one doesn’t feel like it.

Hard work is something valued in the countries of “wet-rice agriculture and meaningful work”, as Gladwell puts it. Based on the research of Boe, the top countries are Singapore (yay!), South Korea, Taiwan, Hong Kong and Japan. Though I’m not so sure of my fellow countryman’s motivations… The parents and children could be driven more by the race for top scores rather than the culture passed on by our forefathers.

Well, I haven’t read much on Boe’s research, but the hardworking nature of my countrymen is fairly accurate. Students are willing to study for long periods of time (most of them anyway…). Adults are willing to work just a little longer, a little harder at work. For example, I recently knew that my friend worked overtime till 4 am at the office. Personally, I think that’s crazy, but to each his (in this case, her) own.

The native language

There was a question in StackOverflow about coding in other spoken languages, which was highlighted in Jeff and Joel’s recent podcast.

The reserved words in a programming language are fixed. Usually they are in English, though there are programming languages in say Chinese. I didn’t know there was a Chinese version of BASIC!

Once, I took up an SQL reference book, written in Chinese. I want to mention that I cannot read a programming reference book written in Chinese. That is to say, I can certainly read the Chinese characters, but I can’t understand the heck what it means.

I need a reference book written in English for SQL, because the native (human) language for SQL is English! Unless there’s a variant I don’t know about…

I’ve seen some code written in Spanish before, I think. Can’t remember. Anyway, the native language for the programming language (C, I think) was English, so the code reads fine. The variable names look different, but I didn’t have too much difficulty.

My guess is that my math background prepared me for abstract notions and symbols, and still be able to work with them. So I treated variables named in a foreign language as just another symbol. And continued to read the code based on that.

And this brings me full circle to…

So does background really matter?

I am unfamiliar with how an American (or English, or French) grows up. I don’t really know the values valued, or the culture surrounding the upbringing of a child.

I do know mine. I’m brought up learning two languages (English and Chinese), two Chinese dialects (Hokkien and Cantonese). I taught myself to read Japanese characters. I’m brought up around people who wake up before dawn to work, and work long hours, regularly and consistently and over long periods of time.

Personal values, personality, genes and luck. I agree they play a part in the makings of a great programmer. In particular, I believe that one’s background influences personal values and personality, so in that sense, background does matter.

And specifically, I think my math background makes grasping programming concepts easier for me.

Of course, everything you’ve just read could be hogwash, because I’m still telling (interesting, I hope) anecdotes to illustrate points as Joel points out vehemently. I haven’t read a lot about computer science and its history in America (or pretty much anywhere in the world). I research just enough so that what I write is as true as I understand it (sometimes I don’t research at all!).

I admit that I’m still naive and easily impressed. I still pretty much trust what I read as true. It’s only when I start internalising the information that I really think about them.

So what do you think?