Oct 192011
 

I fucking did it.

After, what, two years now?

I wanted to start learning iPhone programming. I had a Mac and installed Xcode. I acquired four different books on the subject. I decided, as a learning project, to create a simple app to calculate “mote pools” for my character in Exalted (don’t ask, just roll with it) and track changes in it over the course of a game session.

Almost right away I ran into a wall: how to take four user-determined numbers ranging from 1-5, programmatically determine the two with the highest values, and how to handle a case where two or more had the same value. For example, given: “3, 2, 2, 2”, how do you decide which two 2s to use?

While informative, I reached a point in each book where they just completely lost me, and none of them had an answer to my original problem. Over the course of months, I asked four different programmers I was lucky enough to meet how I might handle it. They all said the same thing: create a static array, plug in the numbers, sort it highest to lowest, and return the top two. That was all well and good but, while they all told me what to do, no one could tell me how to do it, and I didn’t know any of them well enough to make them sit down and show me how to code.

I tried, on multiple occasions, searching the Xcode documentation about NSArray, but it made my head spin because I didn’t know enough to even know what to look for. Eventually I gave up, but it’s stayed at the back of my mind and bugged me ever since. It should not have been that difficult.

Today during lunch I saw an offer on RayWenderlich.com, an iOS programming site I follow on RSS: sign up for their newsletter and get the first “epic-length tutorial” of a new series they’re running, by Matthijs Hollemans, for free. I did, but couldn’t get far in 45 minutes. Since I had the house to myself tonight, I got everything else out of the way when I got home and started working.

I got about halfway through, and had just barely finished the section on if-else statements, when the Eureka moment hit me: I didn’t need to do an array, and I didn’t have to try and compare four numbers at once. I could split them into two pairs, compare each separately, and store the highest one. If neither one was greater than the other, that meant they were equal, and I could arbitrarily take the first member of the pair and store it. Repeat for the second pair. I set the tutorial aside and spent the next two hours coding.

What follows is a mess. It’s ugly. It’s inelegant. I’m sure it could be done half a dozen ways in less than half the amount of code. It will make no sense to you unless you code. In retrospect, I should have figured it out a long time ago.

But it works, and I did it myself.

I’ll be buying the rest of those tutorials come payday.

By the way, WordPress sucks at displaying Rich Text Format.

Scary Code This Way…

%d bloggers like this: